<?php

namespace App\Modules\HR\Employees\Repositories;

use App\Modules\HR\Employees\Enums\EmployeeDocumentType;
use App\Modules\HR\Employees\Models\EmployeeDocument;
use Illuminate\Support\Facades\Storage;

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

    public function replace(
        int $employeeId,
        EmployeeDocumentType $type,
        string $relativePath,
        ?int $uploadedById,
        ?string $expiresAt = null,
    ): EmployeeDocument {
        $existing = $this->findByEmployeeAndType($employeeId, $type);
        if ($existing !== null) {
            Storage::disk('local')->delete($existing->file_path);
            $existing->delete();
        }

        return EmployeeDocument::query()->create([
            'employee_id' => $employeeId,
            'type' => $type->value,
            'file_path' => $relativePath,
            'expires_at' => $expiresAt,
            'uploaded_by' => $uploadedById,
        ]);
    }

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

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