<?php

namespace App\Modules\Payroll\Listeners;

use App\Modules\Admin\ActivityLog\DTOs\ActivityLogWriteData;
use App\Modules\Admin\ActivityLog\Services\ActivityLogService;
use App\Modules\Payroll\Events\PayrollAdjustmentCreated;
use App\Modules\Payroll\Events\PayrollPeriodFinalized;
use App\Modules\Payroll\Events\PayrollSnapshotsGenerated;
use App\Modules\Payroll\Models\PayrollAdjustment;
use App\Modules\Payroll\Models\PayrollPeriod;

class PayrollActivityLogListener
{
    public function __construct(
        private readonly ActivityLogService $activityLog,
    ) {}

    public function handleSnapshotsGenerated(PayrollSnapshotsGenerated $event): void
    {
        $this->write(
            $event->period,
            'payroll_snapshots_generated',
            __('payroll.activity.snapshots_generated', ['id' => $event->period->id]),
            (int) $event->period->created_by,
        );
    }

    public function handleFinalized(PayrollPeriodFinalized $event): void
    {
        $this->write(
            $event->period,
            'payroll_finalized',
            __('payroll.activity.finalized', ['id' => $event->period->id]),
            $event->actorUserId,
        );
    }

    public function handleAdjustment(PayrollAdjustmentCreated $event): void
    {
        $a = $event->adjustment;
        $tid = (int) $a->tenant_id;
        if ($tid < 1) {
            return;
        }
        $this->activityLog->log(new ActivityLogWriteData(
            tenantId: $tid,
            userId: (int) $a->created_by,
            module: 'payroll',
            action: 'payroll_adjustment_created',
            entityType: PayrollAdjustment::class,
            entityId: $a->id,
            description: __('payroll.activity.adjustment_created', [
                'id' => $a->id,
                'period' => $a->payroll_period_id,
                'type' => $a->type,
                'amount' => $a->amount,
                'employee' => $a->employee_id,
                'reason' => $a->reason ?? '',
            ]),
        ));
    }

    private function write(PayrollPeriod $period, string $action, string $description, int $userId): void
    {
        $tid = (int) $period->tenant_id;
        if ($tid < 1) {
            return;
        }
        $this->activityLog->log(new ActivityLogWriteData(
            tenantId: $tid,
            userId: $userId,
            module: 'payroll',
            action: $action,
            entityType: PayrollPeriod::class,
            entityId: $period->id,
            description: $description,
        ));
    }
}
