<?php

namespace App\Components\Contact\Admin;

use App\Enum\Contact\TemplateTriggerType;
use App\Models\Contact\ContactTemplate;
use App\Models\Contact\ContactTemplateTrigger;
use Livewire\Component;

class TriggerManager extends Component
{
    public ?int $editingId = null;
    public array $form = [
        'contact_template_id' => null,
        'trigger_type' => 'status_changed',
        'model_type' => null,
        'conditions' => '{}',
        'dedupe_window_minutes' => 60,
        'is_active' => true,
    ];

    public function mount(): void
    {
        $this->authorize('communications.triggers.manage');
    }

    public function newTrigger(): void
    {
        $this->editingId = 0;
    }

    public function edit(int $id): void
    {
        $t = ContactTemplateTrigger::findOrFail($id);
        $this->editingId = $t->id;
        $this->form = [
            'contact_template_id' => $t->contact_template_id,
            'trigger_type' => $t->trigger_type->value,
            'model_type' => $t->model_type,
            'conditions' => json_encode($t->conditions ?? new \stdClass(), JSON_PRETTY_PRINT),
            'dedupe_window_minutes' => $t->dedupe_window_minutes,
            'is_active' => (bool) $t->is_active,
        ];
    }

    public function save(): void
    {
        $this->authorize('communications.triggers.manage');

        $data = $this->form;
        $data['trigger_type'] = TemplateTriggerType::from($data['trigger_type']);
        $data['conditions'] = json_decode($data['conditions'] ?: '{}', true) ?: null;

        if ($this->editingId) {
            ContactTemplateTrigger::findOrFail($this->editingId)->update($data);
        } else {
            ContactTemplateTrigger::create($data);
        }

        $this->editingId = null;
        $this->reset('form');
    }

    public function delete(int $id): void
    {
        $this->authorize('communications.triggers.manage');
        ContactTemplateTrigger::destroy($id);
    }

    public function render()
    {
        return view('components.contact.admin.trigger-manager', [
            'triggers' => ContactTemplateTrigger::with('template')->orderByDesc('id')->get(),
            'templates' => ContactTemplate::where('allow_automatic_send', true)->orderBy('name')->get(),
            'triggerTypes' => TemplateTriggerType::cases(),
        ]);
    }
}
