<?php

namespace App\Livewire\Modals;

use App\Domains\QrCode\Models\QrCode;
use App\Domains\Workspace\Models\Workspace;
use App\Livewire\Pages\QrCodes\Index;
use Illuminate\View\View;
use LivewireUI\Modal\ModalComponent;

class EditQrCode extends ModalComponent
{
    public int $workspaceId = 0;

    public string $qrUlid = '';

    public string $url = '';

    public string $label = '';

    public string $type = 'url';

    public function mount(string $qrUlid): void
    {
        $qr = QrCode::where('ulid', $qrUlid)->firstOrFail();

        $this->authorizeWorkspace($qr->workspace_id);

        $this->workspaceId = $qr->workspace_id;
        $this->qrUlid = $qrUlid;
        $this->url = $qr->payload['url'] ?? '';
        $this->label = $qr->label ?? '';
        $this->type = $qr->type;
    }

    /** @return array<string, string> */
    protected function rules(): array
    {
        return [
            'url' => 'required|url|max:2048',
            'label' => 'nullable|max:200',
            'type' => 'required|in:url,vcard,wifi,pdf,mp3,text',
        ];
    }

    public function save(): void
    {
        $this->validate();

        $qr = QrCode::where('ulid', $this->qrUlid)
            ->where('workspace_id', $this->workspaceId)
            ->firstOrFail();

        $qr->update([
            'type' => $this->type,
            'payload' => ['url' => $this->url],
        ]);

        $this->dispatch('qr-updated')->to(Index::class);
        $this->dispatch('toast', message: 'QR Code aktualisiert', type: 'success');
        $this->closeModal();
    }

    public static function modalMaxWidth(): string
    {
        return 'md';
    }

    public function render(): View
    {
        return view('livewire.modals.edit-qr-code');
    }

    private function authorizeWorkspace(int $workspaceId): void
    {
        Workspace::where('id', $workspaceId)
            ->where(fn ($q) => $q
                ->where('owner_id', auth()->id())
                ->orWhereHas('members', fn ($q) => $q->where('user_id', auth()->id()))
            )->firstOrFail();
    }
}
