<?php

namespace App\Modules\HR\Attendance\Services;

use App\Models\User;
use App\Modules\Admin\ActivityLog\DTOs\ActivityLogWriteData;
use App\Modules\Admin\ActivityLog\Services\ActivityLogService;
use App\Modules\HR\Attendance\Models\AttendanceException;
use App\Modules\HR\Attendance\Repositories\AttendanceExceptionRepository;
use App\Modules\HR\Attendance\Support\AttendanceExceptionStatus;
use Illuminate\Http\Request;

class AttendanceExceptionReviewService
{
    public function __construct(
        private readonly ActivityLogService $activityLog,
        private readonly AttendanceExceptionRepository $exceptions,
    ) {}

    public function resolve(AttendanceException $exception, User $actor, ?string $note, ?Request $request = null): void
    {
        $this->finalize($exception, $actor, AttendanceExceptionStatus::RESOLVED, $note, 'exception_resolved', $request);
    }

    public function ignore(AttendanceException $exception, User $actor, ?string $note, ?Request $request = null): void
    {
        $this->finalize($exception, $actor, AttendanceExceptionStatus::IGNORED, $note, 'exception_ignored', $request);
    }

    private function finalize(
        AttendanceException $exception,
        User $actor,
        string $status,
        ?string $note,
        string $actionKey,
        ?Request $request,
    ): void {
        $exception->forceFill([
            'status' => $status,
            'resolved_by' => $actor->id,
            'resolved_at' => now(),
            'resolution_note' => $note,
        ])->save();

        $this->exceptions->forgetOperationalSnapshot((int) $exception->tenant_id);

        $this->activityLog->log(
            new ActivityLogWriteData(
                tenantId: (int) $exception->tenant_id,
                userId: (int) $actor->id,
                module: 'attendance',
                action: $actionKey,
                entityType: AttendanceException::class,
                entityId: (int) $exception->id,
                description: __(
                    'attendance_exceptions.activity.'.$actionKey,
                    ['id' => $exception->id, 'type' => $exception->type]
                ),
            ),
            $request,
        );
    }
}
