<?php

namespace App\Http\Requests\Admin;

use App\Models\CommunicationTemplate;
use App\Models\Language;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CommunicationTemplateUpdateRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true; // controller authorize('update', $template) çağırır
    }

    public function rules(): array
    {
        $template = $this->route('communicationTemplate');
        $isEmail = $template && $template->channel === 'email';

        $rules = [
            'contents' => ['required', 'array'],
            'contents.*.language' => [
                'required', 'string', 'max:5',
                Rule::in(Language::active()->pluck('a2_iso')->all()),
            ],
            'contents.*.content' => ['required', 'string'],
        ];

        if ($isEmail) {
            $rules['contents.*.subject'] = ['required', 'string', 'max:255'];
            $rules['name'] = [
                'sometimes', 'string', 'max:255',
                Rule::unique('communication_templates', 'name')
                    ->where('channel', $template->channel)
                    ->ignore($template->id),
            ];
            $rules['type'] = ['sometimes', 'string', Rule::in(CommunicationTemplate::TYPES)];
            $rules['status'] = ['sometimes', 'in:active,inactive'];
            $rules['from_name'] = ['nullable', 'string', 'max:255'];
            $rules['from_address'] = ['nullable', 'email', 'max:255'];
            $rules['copy_address'] = ['nullable', 'email', 'max:255'];
            $rules['bcc_address'] = ['nullable', 'email', 'max:255'];
            $rules['is_html'] = ['sometimes', 'boolean'];
            $rules['message_class'] = ['sometimes', 'in:transactional,marketing'];
        } else {
            // email-dışı kanalda email alanları formdan KABUL EDİLMEZ
            $rules['contents.*.subject'] = ['prohibited'];
            $rules['from_name'] = ['prohibited'];
            $rules['from_address'] = ['prohibited'];
            $rules['copy_address'] = ['prohibited'];
            $rules['bcc_address'] = ['prohibited'];
            $rules['is_html'] = ['prohibited'];
            $rules['message_class'] = ['prohibited'];
            $rules['status'] = ['sometimes', 'in:active,inactive'];
        }

        return $rules;
    }
}
