<?php

namespace App\Modules\HR\Payroll\Services;

use App\Modules\HR\Payroll\DTOs\SalaryStructureWriteData;
use App\Modules\HR\Payroll\Models\SalaryStructure;
use App\Modules\HR\Payroll\Repositories\SalaryStructureRepository;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SalaryStructureService
{
    public function __construct(
        private readonly SalaryStructureRepository $repository,
    ) {}

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

    public function store(SalaryStructureWriteData $data): SalaryStructure
    {
        return DB::transaction(function () use ($data): SalaryStructure {
            $structure = $this->repository->create(array_merge($data->toArray(), [
                'tenant_id' => $this->tenantId(),
            ]));

            $this->repository->syncComponents($structure, $data->components);

            return $structure->fresh('components');
        });
    }

    public function update(SalaryStructure $structure, SalaryStructureWriteData $data): SalaryStructure
    {
        return DB::transaction(function () use ($structure, $data): SalaryStructure {
            $this->repository->update($structure, $data->toArray());
            $this->repository->syncComponents($structure, $data->components);

            return $structure->fresh('components');
        });
    }

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

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

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

        return (int) $id;
    }
}
