<?php

namespace App\Components\Dsar;

use App\Models\Dsar\DsarType;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class TypeEditor extends Component {
    use AuthorizesRequests;
    public $dsarId;
    public $display_name;
    public $description;
    public $content;
    public $email_content;

    protected $rules = [
        'display_name' => 'required|string|max:255',
        'description' => 'nullable|string|max:500',
        'content' => 'required|string',
        'email_content' => 'nullable|string',
    ];

    public function mount($dsarId = null) {
        $this->authorize($dsarId ? 'dsars.types.edit' : 'dsars.types.create');
        if ($dsarId) {
            $type = DsarType::findOrFail($dsarId);
            $this->dsarId = $type->id;
            $this->display_name = $type->display_name;
            $this->description = $type->description;
            $this->content = $type->content;
            $this->email_content = $type->email_content;
        }
    }

    public function save() {
        $this->authorize($this->dsarId ? 'dsars.types.edit' : 'dsars.types.create');
        $this->validate();

        DsarType::updateOrCreate(
            ['id' => $this->dsarId],
            [
                'display_name' => $this->display_name,
                'description' => $this->description,
                'content' => $this->content,
                'email_content' => $this->email_content ?: null,
            ]
        );

        $this->dispatch('toast', message: 'Configuration saved successfully.', type: 'success');
    }

    public function cancel() {
        $this->dispatch('dsar-cancelled');
    }

    public function render() {
        return view('components.dsar.type-editor');
    }
}
