<?php

namespace App\Http\Requests\Admin;

use App\Models\Customer;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CustomerRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $customerId = $this->route('customer')?->id;
        $companyId = $this->user()->company_id ?: $this->input('company_id');

        $rules = [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['nullable', 'email', 'max:255'],
            'phone' => [
                'nullable', 'string', 'max:50',
                Rule::unique('customers', 'phone')->ignore($customerId)->where(fn ($q) => $q->where('company_id', $companyId)),
            ],
            'status' => ['required', Rule::in(['active', 'inactive'])],
            'tag' => ['nullable', Rule::in(array_keys(Customer::TAGS))],
        ];

        if (! $this->user()->company_id) {
            $rules['company_id'] = ['required', 'exists:companies,id'];
        }

        return $rules;
    }
}
