<?php

namespace App\Modules\HR\Contracts\Repositories;

use App\Modules\HR\Contracts\Models\EmploymentContract;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;

class EmploymentContractRepository
{
    /**
     * @param  array<string, mixed>  $data
     */
    public function create(array $data): EmploymentContract
    {
        return EmploymentContract::query()->create($data);
    }

    public function findForTenant(int $tenantId, int $id): ?EmploymentContract
    {
        return EmploymentContract::query()
            ->where('tenant_id', $tenantId)
            ->whereKey($id)
            ->first();
    }

    public function paginateForTenant(int $tenantId, int $perPage = 20): LengthAwarePaginator
    {
        return EmploymentContract::query()
            ->where('tenant_id', $tenantId)
            ->with(['employee', 'template'])
            ->orderByDesc('start_date')
            ->paginate($perPage);
    }

    public function expiringWithinDays(int $tenantId, int $days): Collection
    {
        return EmploymentContract::query()
            ->where('tenant_id', $tenantId)
            ->where('status', 'active')
            ->whereBetween('end_date', [today(), today()->addDays($days)])
            ->with('employee')
            ->orderBy('end_date')
            ->get();
    }

    /**
     * @param  array<string, mixed>  $data
     */
    public function update(EmploymentContract $contract, array $data): EmploymentContract
    {
        $contract->update($data);

        return $contract->fresh(['employee']);
    }
}
