<?php

namespace App\Http\Requests;

use App\Models\AttendanceEnrollment;
use App\Support\StaffAttendance;
use App\Support\StaffType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

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

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'attendance_device_id' => ['required', 'integer', 'exists:attendance_devices,id'],
            '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.'));
                    }
                },
            ],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            if ($validator->errors()->isNotEmpty()) {
                return;
            }

            $deviceId = $this->integer('attendance_device_id');
            $staffType = $this->string('staff_type')->toString();
            $staffId = $this->integer('staff_id');

            $alreadyEnrolled = AttendanceEnrollment::query()
                ->where('attendance_device_id', $deviceId)
                ->where('staff_type', $staffType)
                ->where('staff_id', $staffId)
                ->exists();

            if ($alreadyEnrolled) {
                $validator->errors()->add(
                    'staff_id',
                    __('This staff member is already enrolled on the selected device.'),
                );

                return;
            }

            $deviceUserId = (string) $staffId;

            $deviceUserTaken = AttendanceEnrollment::query()
                ->where('attendance_device_id', $deviceId)
                ->where('device_user_id', $deviceUserId)
                ->where(function ($query) use ($staffType, $staffId): void {
                    $query->where('staff_type', '!=', $staffType)
                        ->orWhere('staff_id', '!=', $staffId);
                })
                ->exists();

            if ($deviceUserTaken) {
                $validator->errors()->add(
                    'staff_id',
                    __('Another staff member is already enrolled on this device with the same ID number.'),
                );
            }
        });
    }
}
