<?php

namespace App\Modules\HR\Leave\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Leave\DTOs\LeaveRequestSubmitData;
use App\Modules\HR\Leave\Models\LeaveRequest;
use App\Modules\HR\Leave\Repositories\LeaveRequestRepository;
use App\Modules\HR\Leave\Repositories\LeaveTypeRepository;
use App\Modules\HR\Leave\Requests\StoreLeaveRequestRequest;
use App\Modules\HR\Leave\Services\LeaveApprovalService;
use App\Modules\HR\Leave\Services\LeaveCancellationService;
use App\Modules\HR\Leave\Services\LeaveRequestService;
use App\Modules\HR\Leave\Services\LeaveTypeBootstrapService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class LeaveRequestsPageController extends Controller
{
    public function __construct(
        private readonly LeaveRequestRepository $requests,
        private readonly LeaveTypeRepository $types,
        private readonly LeaveTypeBootstrapService $typeBootstrap,
        private readonly LeaveRequestService $submit,
        private readonly LeaveApprovalService $approval,
        private readonly LeaveCancellationService $cancellation,
    ) {}

    public function index(): View
    {
        $this->authorize('viewAny', LeaveRequest::class);
        $tenant = $this->tenant();

        return view('pages.hr.leave.index', [
            'requests' => $this->requests->paginateForTenant((int) $tenant->id),
        ]);
    }

    public function create(): View
    {
        $this->authorize('create', LeaveRequest::class);
        $tenant = $this->tenant();
        $this->typeBootstrap->ensureDefaults($tenant);

        return view('pages.hr.leave.create', [
            'types' => $this->types->activeForTenant((int) $tenant->id),
            'employees' => Employee::query()->where('tenant_id', $tenant->id)->orderBy('full_name')->get(),
        ]);
    }

    public function store(StoreLeaveRequestRequest $request): RedirectResponse
    {
        $tenant = $this->tenant();
        $this->submit->submit(
            $tenant,
            LeaveRequestSubmitData::fromValidated($request->validated()),
            (int) $request->user()->id,
            $request->file('attachment'),
        );

        return redirect()->route('hr.leave.requests.index')->with('status', __('leave.flash.submitted'));
    }

    public function approveManager(int $leaveRequest): RedirectResponse
    {
        return $this->transition($leaveRequest, 'approveManager', fn ($row, $user) => $this->approval->approveManager($row, $user), 'manager_approved');
    }

    public function approveHr(int $leaveRequest): RedirectResponse
    {
        return $this->transition($leaveRequest, 'approveHr', fn ($row, $user) => $this->approval->approveHr($row, $user), 'hr_approved');
    }

    public function reject(int $leaveRequest): RedirectResponse
    {
        return $this->transition($leaveRequest, 'reject', fn ($row, $user) => $this->approval->reject($row, $user), 'rejected');
    }

    public function cancel(int $leaveRequest): RedirectResponse
    {
        return $this->transition($leaveRequest, 'cancel', fn ($row, $user) => $this->cancellation->cancel($row, $user), 'cancelled');
    }

    /**
     * @param  callable(\App\Modules\HR\Leave\Models\LeaveRequest, \App\Models\User): mixed  $action
     */
    private function transition(int $leaveRequest, string $ability, callable $action, string $flashKey): RedirectResponse
    {
        $tenant = $this->tenant();
        $row = $this->requests->findForTenant((int) $tenant->id, $leaveRequest);
        abort_if($row === null, 404);
        $this->authorize($ability, $row);
        $action($row, request()->user());

        return redirect()->route('hr.leave.requests.index')->with('status', __('leave.flash.'.$flashKey));
    }

    private function tenant(): \App\Modules\Admin\Tenancy\Models\Tenant
    {
        $t = auth()->user()?->tenant;
        abort_if($t === null, 403);

        return $t;
    }
}
