<?php

declare(strict_types=1);

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

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Maestro\Core\Modules\HourRegistration\Enums\HourRegistrationType;

class HourSyncTimesheetWeekRequest extends FormRequest
{
    public function authorize(): bool
    {
        return Auth::guard()->user()?->can('hours.week.manage') ?? false;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $dayRules = [];

        foreach (['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as $day) {
            $dayRules["lines.*.duration_{$day}"] = ['nullable', 'numeric', 'min:0', 'max:24'];
        }

        /** @phpstan-ignore-next-line */
        $registrationValues = implode(',', array_column(HourRegistrationType::cases(), 'value'));

        return array_merge([
            'lines' => ['present', 'array'],
            'lines.*.id' => ['sometimes', 'integer'],
            'lines.*.registration_type' => ['required', 'string', 'in:'.$registrationValues],
            'lines.*.internal_category_id' => ['nullable', 'integer', 'exists:hour_internal_categories,id'],
            'lines.*.customer_id' => ['nullable', 'integer', 'exists:customers,id'],
            'lines.*.hour_project_id' => ['nullable', 'integer', 'exists:hour_projects,id'],
            'lines.*.hour_task_id' => ['nullable', 'integer', 'exists:hour_tasks,id'],
            'lines.*.description' => ['nullable', 'string', 'max:500'],
            'removed_line_ids' => ['sometimes', 'array'],
            'removed_line_ids.*' => ['integer', 'exists:hour_timesheet_lines,id'],
        ], $dayRules);
    }
}
