<?php

namespace App\Modules\HR\EmployeeSelfService\Requests;

use App\Modules\HR\Leave\Models\LeaveRequest;
use App\Modules\HR\Leave\Repositories\LeaveTypeRepository;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class MeStoreLeaveRequestRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('create', LeaveRequest::class) ?? false;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $tenantId = $this->user()?->tenant_id;

        return [
            'leave_type_id' => [
                'required',
                'integer',
                Rule::exists('leave_types', 'id')->where(fn ($q) => $q->where('tenant_id', $tenantId)),
            ],
            'start_date' => ['required', 'date'],
            'end_date' => ['required', 'date', 'after_or_equal:start_date'],
            'is_half_day' => ['sometimes', 'boolean'],
            'hours_requested' => ['nullable', 'numeric', 'min:0.25', 'max:24'],
            'reason' => ['nullable', 'string', 'max:5000'],
            'attachment' => [
                Rule::requiredIf(fn () => $this->typeRequiresAttachment((int) $tenantId)),
                'nullable',
                'file',
                'max:10240',
                'mimes:pdf,doc,docx,jpg,jpeg,png',
            ],
        ];
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'is_half_day' => $this->boolean('is_half_day'),
        ]);
    }

    private function typeRequiresAttachment(int $tenantId): bool
    {
        $typeId = (int) $this->input('leave_type_id');
        if ($typeId < 1 || $tenantId < 1) {
            return false;
        }
        $type = app(LeaveTypeRepository::class)->findForTenant($tenantId, $typeId);

        return (bool) ($type?->requires_attachment);
    }
}
