<?php

namespace App\Modules\HR\Contracts\Services;

use App\Modules\HR\Contracts\DTOs\ContractWriteData;
use App\Modules\HR\Contracts\Models\EmploymentContract;
use App\Modules\HR\Contracts\Repositories\EmploymentContractRepository;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

class EmploymentContractService
{
    public function __construct(
        private readonly EmploymentContractRepository $repository,
    ) {}

    public function store(ContractWriteData $data, ?UploadedFile $attachment, int $userId): EmploymentContract
    {
        $tenantId = $this->tenantId();
        $path = $attachment !== null
            ? $attachment->store("tenants/{$tenantId}/contracts", 'local')
            : null;

        return $this->repository->create(array_merge($data->toArray(), [
            'tenant_id' => $tenantId,
            'attachment_path' => $path,
            'created_by' => $userId,
        ]));
    }

    public function update(
        EmploymentContract $contract,
        ContractWriteData $data,
        ?UploadedFile $attachment,
    ): EmploymentContract {
        $payload = $data->toArray();
        if ($attachment !== null) {
            $tenantId = (int) $contract->tenant_id;
            if ($contract->attachment_path) {
                Storage::disk('local')->delete($contract->attachment_path);
            }
            $payload['attachment_path'] = $attachment->store("tenants/{$tenantId}/contracts", 'local');
        }

        return $this->repository->update($contract, $payload);
    }

    public function deactivate(EmploymentContract $contract): void
    {
        if (! $contract->is_active) {
            return;
        }
        $this->repository->update($contract, ['is_active' => false]);
    }

    private function tenantId(): int
    {
        $id = auth()->user()?->tenant_id;
        if ($id === null) {
            abort(403);
        }

        return (int) $id;
    }
}
