<?php

namespace App\Modules\HR\Employees\Repositories;

use App\Modules\HR\Employees\Enums\EmployeeDocumentType;
use App\Modules\HR\Employees\Models\EmployeeDocument;

class EmployeeDocumentRepository
{
    public function findByEmployeeAndType(int $employeeId, EmployeeDocumentType $type): ?EmployeeDocument
    {
        return EmployeeDocument::query()
            ->where('employee_id', $employeeId)
            ->where('type', $type->value)
            ->where('status', 'active')
            ->latest('version')
            ->first();
    }

    public function replace(
        int $employeeId,
        EmployeeDocumentType $type,
        string $relativePath,
        ?int $uploadedById,
        ?string $expiresAt = null,
    ): EmployeeDocument {
        $existing = $this->findByEmployeeAndType($employeeId, $type);
        if ($existing !== null) {
            $existing->update(['status' => 'replaced']);
        }

        return EmployeeDocument::query()->create([
            'employee_id' => $employeeId,
            'type' => $type->value,
            'file_path' => $relativePath,
            'expires_at' => $expiresAt,
            'uploaded_by' => $uploadedById,
            'category' => $type->value,
            'status' => 'active',
            'version' => ($existing?->version ?? 0) + 1,
            'replaces_document_id' => $existing?->id,
        ]);
    }

    public function updateExpiry(int $employeeId, EmployeeDocumentType $type, string $expiresAt): void
    {
        $existing = $this->findByEmployeeAndType($employeeId, $type);
        if ($existing === null) {
            return;
        }

        $existing->update(['expires_at' => $expiresAt]);
    }
}
