<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Models\EmailTemplate;

class EmailTemplateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'subject' => 'required|string|max:255',
            'body' => 'required|string',
            'isActive' => 'required|boolean',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            // Get the template being updated
            $templateId = $this->route('id');
            $template = EmailTemplate::find($templateId);

            if (!$template) {
                return;
            }

            // Extract variables from body
            preg_match_all('/\{\{([^}]+)\}\}/', $this->body, $matches);
            $usedVariables = array_map(fn($var) => '{{' . $var . '}}', $matches[1]);

            // Get allowed variables for this template type
            $allowedVariables = $template->variables;

            // Check for invalid variables
            $invalidVars = array_diff($usedVariables, $allowedVariables);

            if (count($invalidVars) > 0) {
                $validator->errors()->add(
                    'body',
                    'Template contains invalid variables: ' . implode(', ', $invalidVars)
                );
            }
        });
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'subject.required' => 'Email subject is required',
            'body.required' => 'Email body is required',
            'isActive.required' => 'Active status is required',
        ];
    }
}
