<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class AppointmentUpdateRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->user()->role === 'provider';
    }

    public function rules(): array
    {
        $provider = auth()->user()->provider;
        
        return [
            'start_time' => 'required|date',
            'end_time' => 'required|date|after:start_time',
            'client_id' => [
                'nullable',
                'exists:clients,id',
                function ($attribute, $value, $fail) use ($provider) {
                    if ($value && !$provider->clients()->where('id', $value)->exists()) {
                        $fail('Le client sélectionné n\'appartient pas à votre compte.');
                    }
                }
            ],
            'service_id' => [
                'nullable',
                'exists:services,id',
                function ($attribute, $value, $fail) use ($provider) {
                    if ($value && !$provider->services()->where('id', $value)->exists()) {
                        $fail('Le service sélectionné n\'appartient pas à votre compte.');
                    }
                }
            ],
            'price_at_booking' => 'nullable|numeric|min:0',
            'currency' => 'nullable|string|size:3',
            'status' => 'required|in:scheduled,completed,canceled,no_show',
            'notes' => 'nullable|string',
        ];
    }
}