<?php

namespace App\Http\Requests;

use App\Support\AttendancePunchType;
use App\Support\StaffAttendance;
use App\Support\StaffType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreManualAttendancePunchRequest extends FormRequest
{
    public function authorize(): bool
    {
        return (bool) $this->user()?->can('attendance.create');
    }

    protected function prepareForValidation(): void
    {
        $deviceId = $this->input('attendance_device_id');

        if ($deviceId === '' || $deviceId === null) {
            $this->merge(['attendance_device_id' => null]);
        }
    }

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'staff_type' => ['required', 'string', Rule::in(StaffType::values())],
            'staff_id' => [
                'required',
                'integer',
                function (string $attribute, mixed $value, \Closure $fail): void {
                    $staffType = $this->string('staff_type')->toString();

                    if (StaffAttendance::findStaff($staffType, (int) $value) === null) {
                        $fail(__('The selected staff member does not exist.'));
                    }
                },
            ],
            'punched_at' => ['required', 'date'],
            'punch_type' => ['required', 'string', Rule::in(AttendancePunchType::values())],
            'attendance_device_id' => ['nullable', 'integer', 'exists:attendance_devices,id'],
        ];
    }
}
