<?php

namespace App\Support;

use App\Models\TemporaryEmployeeContract;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Schema;

class ContractStatus
{
    public static function isEnabled(): bool
    {
        return Schema::hasColumn(
            (new TemporaryEmployeeContract)->getTable(),
            'status',
        );
    }

    public static function resolveForEndDate(string $toDate): string
    {
        $end = Carbon::parse($toDate)->startOfDay();
        $today = now()->startOfDay();

        if ($end->lt($today)) {
            return TemporaryEmployeeContract::STATUS_TERMINATED;
        }

        return TemporaryEmployeeContract::STATUS_ACTIVE;
    }

    public static function terminateExpired(?int $temporaryEmployeeId = null): int
    {
        if (! self::isEnabled()) {
            return 0;
        }

        return self::expiredActiveQuery($temporaryEmployeeId)->update([
            'status' => TemporaryEmployeeContract::STATUS_TERMINATED,
        ]);
    }

    /**
     * @return Builder<TemporaryEmployeeContract>
     */
    public static function expiredActiveQuery(?int $temporaryEmployeeId = null): Builder
    {
        return TemporaryEmployeeContract::query()
            ->when($temporaryEmployeeId !== null, function (Builder $query) use ($temporaryEmployeeId): void {
                $query->where('temporary_employee_id', $temporaryEmployeeId);
            })
            ->where('status', TemporaryEmployeeContract::STATUS_ACTIVE)
            ->whereDate('to_date', '<', now()->toDateString());
    }
}
