<?php

namespace App\Modules\HR\PermissionRequests\Services;

use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\PermissionRequests\DTOs\PermissionRequestSubmitData;
use App\Modules\HR\PermissionRequests\Events\PermissionRequestSubmitted;
use App\Modules\HR\PermissionRequests\Models\PermissionRequest;
use App\Modules\HR\PermissionRequests\Repositories\PermissionRequestRepository;
use App\Modules\HR\PermissionRequests\Support\PermissionRequestStatus;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Facades\DB;

class PermissionRequestService
{
    public function __construct(
        private readonly PermissionRequestRepository $requests,
        private readonly Dispatcher $events,
    ) {}

    public function submit(Tenant $tenant, PermissionRequestSubmitData $data, int $userId): PermissionRequest
    {
        return DB::transaction(function () use ($tenant, $data, $userId): PermissionRequest {
            $row = $this->requests->create([
                'tenant_id' => $tenant->id,
                'employee_id' => $data->employeeId,
                'requested_by' => $userId,
                'type' => $data->type,
                'request_date' => CarbonImmutable::parse($data->requestDate)->toDateString(),
                'start_at' => $data->startAt,
                'end_at' => $data->endAt,
                'reason' => $data->reason,
                'status' => PermissionRequestStatus::PENDING,
            ]);
            $fresh = $row->fresh(['employee']) ?? $row;
            DB::afterCommit(function () use ($fresh, $userId): void {
                $this->events->dispatch(new PermissionRequestSubmitted($fresh, $userId));
            });

            return $fresh;
        });
    }
}
