<?php

namespace App\Modules\Payroll\Services;

use App\Modules\Payroll\Events\PayrollAdjustmentCreated;
use App\Modules\Payroll\Repositories\PayrollAdjustmentRepository;
use App\Modules\Payroll\Support\PayrollAdjustmentType;
use Illuminate\Contracts\Events\Dispatcher;

class PayrollOvertimeAdjustmentSyncService
{
    public function __construct(
        private readonly PayrollAdjustmentRepository $adjustments,
        private readonly PayrollOvertimeAmountCalculator $calculator,
        private readonly Dispatcher $events,
    ) {}

    public function syncForEmployee(
        int $tenantId,
        int $employeeId,
        int $payrollPeriodId,
        float $baseSalary,
        int $overtimeMinutes,
        ?int $actorUserId,
    ): void {
        if (! config('payroll.auto_overtime_adjustment', true)) {
            return;
        }

        $this->adjustments->deleteSystemOvertimeForEmployeePeriod($tenantId, $employeeId, $payrollPeriodId);
        if ($overtimeMinutes <= 0) {
            return;
        }

        $amount = $this->calculator->amountFromMinutes($baseSalary, $overtimeMinutes);
        if ((float) $amount <= 0) {
            return;
        }

        $adj = $this->adjustments->create([
            'tenant_id' => $tenantId,
            'employee_id' => $employeeId,
            'payroll_period_id' => $payrollPeriodId,
            'type' => PayrollAdjustmentType::OVERTIME,
            'amount' => $amount,
            'reason' => 'Auto OT '.$overtimeMinutes.'m',
            'created_by' => $actorUserId,
        ]);
        $this->events->dispatch(new PayrollAdjustmentCreated($adj));
    }
}
