<?php

namespace App\Http\Requests\Admin;

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

/**
 * PRC-619 / PRC-624 §2.6 — create tüm kanallar için açık (email + sms +
 * admin kanalları slack/telegram/discord/whatsapp/pushover). Alan listesi/
 * zorunluluklar: email kendi alanları; sms ve admin kanalları aynı (ad+tip+
 * status, email-only alanlar yasak).
 */
class CommunicationTemplateStoreRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true; // controller authorize('create', ...) çağırır
    }

    public function rules(): array
    {
        $channel = (string) $this->input('channel');
        $allChannels = array_merge(CommunicationTemplate::CLIENT_CHANNELS, CommunicationTemplate::ADMIN_CHANNELS);

        $rules = [
            'channel' => ['required', Rule::in($allChannels)],
            'name' => [
                'required', 'string', 'max:255',
                Rule::unique('communication_templates', 'name')->where('channel', $channel),
            ],
        ];

        if ($channel !== 'email') {
            // sms + admin kanalları (slack/telegram/discord/whatsapp/pushover):
            // ad+tip+status; email-only alanlar yasak. Tip whitelist'i tek kaynak.
            $rules['type'] = ['required', 'string', Rule::in(CommunicationTemplate::TYPES)];
            $rules['status'] = ['sometimes', Rule::in(['active', 'inactive'])];
            // email-only alanlar diğer kanallarda kabul edilmez
            $rules['from_name'] = ['prohibited'];
            $rules['from_address'] = ['prohibited'];
            $rules['copy_address'] = ['prohibited'];
            $rules['bcc_address'] = ['prohibited'];
            $rules['message_class'] = ['prohibited'];
        } else {
            // Tip whitelist'i tek kaynak: CommunicationTemplate::TYPES (PRC-619 review)
            $rules['type'] = ['required', 'string', Rule::in(\App\Models\CommunicationTemplate::TYPES)];
            $rules['from_name'] = ['required', 'string', 'max:255'];
            $rules['from_address'] = ['required', 'email', 'max:255'];
            $rules['copy_address'] = ['nullable', 'email', 'max:255'];
            $rules['bcc_address'] = ['nullable', 'email', 'max:255'];
            $rules['status'] = ['required', Rule::in(['active', 'inactive'])];
            $rules['message_class'] = ['nullable', Rule::in(['transactional', 'marketing'])];
        }

        return $rules;
    }
}
