<?php

namespace App\Modules\HR\EmploymentStatuses\Services;

use App\Modules\HR\EmploymentStatuses\DTOs\EmploymentStatusWriteData;
use App\Modules\HR\EmploymentStatuses\Models\EmploymentStatus;
use App\Modules\HR\EmploymentStatuses\Repositories\EmploymentStatusRepository;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class EmploymentStatusService
{
    public function __construct(
        private readonly EmploymentStatusRepository $repository,
    ) {}

    public function list(): Collection
    {
        return $this->repository->listOrdered();
    }

    public function paginateForIndex(Request $request): LengthAwarePaginator
    {
        return $this->repository->paginateForIndex($request);
    }

    public function store(EmploymentStatusWriteData $data): EmploymentStatus
    {
        $tenantId = $this->tenantId();

        return $this->repository->create(array_merge($data->toArray(), [
            'tenant_id' => $tenantId,
            'code' => $this->uniqueCode($tenantId, $data->name),
        ]));
    }

    public function update(EmploymentStatus $status, EmploymentStatusWriteData $data): EmploymentStatus
    {
        return $this->repository->update($status, $data->toArray());
    }

    public function deactivate(EmploymentStatus $status): void
    {
        if (! $status->is_active) {
            return;
        }

        $this->repository->update($status, ['is_active' => false]);
    }

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

        return (int) $id;
    }

    private function uniqueCode(int $tenantId, string $name): string
    {
        $base = Str::limit(Str::slug($name), 48, '') ?: 'status';
        $code = $base;
        $suffix = 1;

        while (EmploymentStatus::query()->where('tenant_id', $tenantId)->where('code', $code)->exists()) {
            $code = $base.'-'.$suffix++;
        }

        return $code;
    }
}
