<?php

namespace App\Domain\Rent\Support;

use App\Models\Lease;
use Illuminate\Validation\ValidationException;

class LeaseOverlapGuard
{
    public static function ensureNoOverlap(
        int $unitId,
        string $startDate,
        ?string $endDate,
        ?int $ignoreLeaseId = null
    ): void {
        $q = Lease::query()
            ->where('unit_id', $unitId)
            ->where('status', 'active');

        if ($ignoreLeaseId) $q->where('id','!=',$ignoreLeaseId);

        // overlap check: (existing.start <= newEnd) AND (existing.end >= newStart)
        $newStart = $startDate;
        $newEnd   = $endDate ?? '9999-12-31';

        $q->whereDate('start_date', '<=', $newEnd)
          ->whereRaw('COALESCE(end_date, "9999-12-31") >= ?', [$newStart]);

        if ($q->exists()) {
            throw ValidationException::withMessages([
                'unit_id' => 'Kontrak aktif overlap pada ruko yang sama.',
            ]);
        }
    }
}
