<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        $provider = auth()->user()->provider;
        
        return [
            'expense_type_id' => [
                'required',
                'exists:expense_types,id',
                function ($attribute, $value, $fail) use ($provider) {
                    if (!$provider->expenseTypes()->where('id', $value)->exists()) {
                        $fail('Le type de dépense sélectionné n\'appartient pas à votre compte.');
                    }
                }
            ],
            'supplier_id' => [
                'nullable',
                'exists:suppliers,id',
                function ($attribute, $value, $fail) use ($provider) {
                    if ($value && !$provider->suppliers()->where('id', $value)->exists()) {
                        $fail('Le fournisseur sélectionné n\'appartient pas à votre compte.');
                    }
                }
            ],
            'amount' => 'required|numeric|min:0',
            'currency' => 'nullable|string|size:3',
            'expense_date' => 'required|date',
            'payment_method' => 'required|in:cash,card,bank_transfer,other',
            'reference' => 'nullable|string|max:150',
            'notes' => 'nullable|string',
        ];
    }
}