<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\HourRegistration\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maestro\Core\Http\Controllers\Controller;
use Maestro\Core\Modules\HourRegistration\Http\Requests\HourRejectLineRequest;
use Maestro\Core\Modules\HourRegistration\Http\Resources\HourTimesheetLineResource;
use Maestro\Core\Modules\HourRegistration\Models\HourTimesheetLine;
use Maestro\Core\Modules\HourRegistration\Services\HourLineApprovalService;

class HourApprovalController extends Controller
{
    public function pending(Request $request, HourLineApprovalService $approvals): JsonResponse
    {
        abort_unless($request->user()?->can('hours.approve') || $request->user()?->can('hours.admin'), 403);

        $lines = $approvals->pendingLinesForActor($request->user())->values();

        return HourTimesheetLineResource::collection($lines)->response();
    }

    public function approve(Request $request, HourTimesheetLine $hour_timesheet_line, HourLineApprovalService $approvals): JsonResponse
    {
        $approved = $approvals->approve($hour_timesheet_line, $request->user());

        return (new HourTimesheetLineResource($approved))->response();
    }

    public function reject(HourRejectLineRequest $request, HourTimesheetLine $hour_timesheet_line, HourLineApprovalService $approvals): JsonResponse
    {
        $line = $approvals->reject($hour_timesheet_line, trim((string) $request->input('reason')), $request->user());

        return (new HourTimesheetLineResource($line))->response();
    }
}
