<?php

namespace App\Components\Dsar;

use App\Models\Dsar\DsarType;
use Livewire\Component;

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

    protected $rules = [
        'display_name' => 'required|string|max:255',
        'description' => 'nullable|string|max:500',
        'content' => 'required|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;
        }
    }

    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,
            ]
        );

        $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');
    }
}
