<?php

namespace App\Http\Requests;

use App\Enums\DefaultStatusEnum;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StateRequest extends FormRequest
{
    public function rules(): array
    {
        $rules = [
            'name'       => 'sometimes|string|max:255',
            'code'       => 'sometimes|string|size:2',
            'country_id' => 'sometimes|exists:countries,id',
            'status'     => ['sometimes', Rule::enum(DefaultStatusEnum::class)],
        ];

        if ($this->isMethod('post')) {
            $rules['name'] = [
                'required',
                'string',
                'max:255',
                Rule::unique('states')->where(function ($query) {
                    return $query->where('country_id', $this->country_id);
                }),
            ];

            $rules['code'] = [
                'required',
                'string',
                'size:2',
                Rule::unique('states')->where(function ($query) {
                    return $query->where('country_id', $this->country_id);
                }),
            ];

            $rules['country_id'] = 'required|exists:countries,id';
            $rules['status']     = ['required', Rule::enum(DefaultStatusEnum::class)];
        }

        return $rules;
    }
}
