<?php

namespace App\Modules\HR\Leave\Services;

use App\Modules\HR\Leave\DTOs\LeaveTypeWriteData;
use App\Modules\HR\Leave\Models\LeaveType;
use App\Modules\HR\Leave\Repositories\LeaveTypeRepository;
use Illuminate\Database\Eloquent\Collection;

class LeaveTypeService
{
    public function __construct(
        private readonly LeaveTypeRepository $repository,
        private readonly LeaveTypeBootstrapService $bootstrap,
    ) {}

    public function list(): Collection
    {
        $user = auth()->user();
        $tenantId = (int) ($user?->tenant_id ?? 0);
        if ($tenantId < 1 || $user?->tenant === null) {
            abort(403);
        }
        $this->bootstrap->ensureDefaults($user->tenant);

        return $this->repository->listForTenant($tenantId);
    }

    public function store(LeaveTypeWriteData $data): LeaveType
    {
        return $this->repository->create(array_merge($data->toArray(), [
            'tenant_id' => $this->tenantId(),
        ]));
    }

    public function update(LeaveType $type, LeaveTypeWriteData $data): LeaveType
    {
        return $this->repository->update($type, $data->toArray());
    }

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

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

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

        return (int) $id;
    }
}
