<?php

namespace App\Jobs;

use App\Models\PayrollRun;
use App\Services\Payroll\PayrollCalculator;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Throwable;

class CalculatePayrollRun implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public int $timeout = 900;

    public function __construct(public PayrollRun $run) {}

    public function handle(PayrollCalculator $calculator): void
    {
        // Clear any prior payslips in one statement (payslip_lines cascade at the
        // DB level). A chunked ->each(delete) would skip rows as pages shift.
        $this->run->payslips()->delete();
        $this->run->update(['status' => PayrollRun::STATUS_PROCESSING, 'notes' => null]);

        try {
            $calculator->run($this->run->fresh()); // sets status -> CALCULATED on success
        } catch (Throwable $e) {
            $this->run->update([
                'status' => PayrollRun::STATUS_FAILED,
                'notes' => mb_substr($e->getMessage(), 0, 1000),
            ]);
            throw $e;
        }
    }

    public function failed(Throwable $e): void
    {
        $this->run->update([
            'status' => PayrollRun::STATUS_FAILED,
            'notes' => mb_substr($e->getMessage(), 0, 1000),
        ]);
    }
}
