<?php
// app/Http/Requests/Api/Admin/UserRequest.php

namespace App\Http\Requests\Api\Admin;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    public function rules(): array
    {
        $userId = $this->route('id');

        $rules = [
            'name' => 'required|string|max:255',
            'email' => [
                'required',
                'email',
                'max:255',
                Rule::unique('users')->ignore($userId)
            ],
            'phone' => [
                'required',
                'string',
                'max:20',
                Rule::unique('users')->ignore($userId)
            ],
            'role' => 'required|in:customer,employee,admin',
        ];

        // Password rules
        if ($this->isMethod('POST')) {
            // Create - password required
            $rules['password'] = 'required|string|min:6|confirmed';
            $rules['password_confirmation'] = 'required|string|min:6';
        } else {
            // Update - password optional
            $rules['password'] = 'nullable|string|min:6|confirmed';
            $rules['password_confirmation'] = 'nullable|string|min:6';
        }

        return $rules;
    }

    public function messages(): array
    {
        return [
            'email.unique' => 'Email sudah digunakan',
            'phone.unique' => 'Nomor telepon sudah digunakan',
            'password.confirmed' => 'Konfirmasi password tidak cocok',
        ];
    }
}