<?php

namespace App\Http\Requests;

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

class CityRequest extends FormRequest
{
    public function rules(): array
    {
        $rules = [
            'name'       => 'sometimes|string|max:255',
            'country_id' => 'sometimes|exists:countries,id',

            'state_id' => [
                'sometimes',
                'exists:states,id',
            ],

            'status' => ['sometimes', Rule::enum(DefaultStatusEnum::class)],
        ];

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

            $rules['country_id'] = 'required|exists:countries,id';

            $rules['state_id'] = [
                'required',
                'exists:states,id',
            ];

            $rules['status'] = ['required', Rule::enum(DefaultStatusEnum::class)];
        }

        return $rules;
    }
}
