<?php

namespace App\Modules\Payroll\Services;

use App\Models\User;
use App\Modules\Payroll\Events\PayrollPeriodFinalized;
use App\Modules\Payroll\Models\PayrollPeriod;
use App\Modules\Payroll\Repositories\PayrollPeriodRepository;
use Illuminate\Support\Facades\DB;

class PayrollFinalizationService
{
    public function __construct(
        private readonly PayrollPeriodRepository $periods,
    ) {}

    public function finalize(PayrollPeriod $period, User $user): PayrollPeriod
    {
        $tid = (int) $period->tenant_id;
        $pid = (int) $period->id;
        $updated = $this->periods->finalizeFromProcessingIfEligible($tid, $pid, (int) $user->id);
        if ($updated === null) {
            $current = $this->periods->findForTenant($tid, $pid);
            if ($current !== null && $current->isFinalized()) {
                abort(422, 'Already finalized.');
            }
            abort(422, 'Payroll can only be finalized from processing state.');
        }
        DB::afterCommit(function () use ($updated, $user): void {
            event(new PayrollPeriodFinalized($updated, (int) $user->id));
        });

        return $updated;
    }
}
