<?php

namespace App\Livewire\Modals;

use App\Domains\Link\Models\Link;
use App\Domains\Workspace\Models\Workspace;
use App\Livewire\Pages\Links\Index;
use Illuminate\View\View;
use LivewireUI\Modal\ModalComponent;

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

    public string $linkUlid = '';

    public int $linkId = 0;

    public string $targetUrl = '';

    public string $slug = '';

    public string $title = '';

    public string $status = 'active';

    public function mount(string $linkUlid): void
    {
        $link = Link::where('ulid', $linkUlid)->firstOrFail();

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

        $this->workspaceId = $link->workspace_id;
        $this->linkUlid = $linkUlid;
        $this->linkId = $link->id;
        $this->targetUrl = $link->target_url;
        $this->slug = $link->slug;
        $this->title = $link->title ?? '';
        $this->status = $link->status;
    }

    /** @return array<string, string> */
    protected function rules(): array
    {
        return [
            'targetUrl' => 'required|url|max:2048',
            'slug' => 'required|alpha_dash|max:50|unique:links,slug,'.$this->linkId,
            'title' => 'nullable|max:200',
            'status' => 'required|in:active,inactive',
        ];
    }

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

        $link = Link::where('ulid', $this->linkUlid)
            ->where('workspace_id', $this->workspaceId)
            ->firstOrFail();

        $link->update([
            'target_url' => $this->targetUrl,
            'slug' => $this->slug,
            'title' => $this->title ?: null,
            'status' => $this->status,
        ]);

        $this->dispatch('link-updated', linkUlid: $this->linkUlid)->to(Index::class);
        $this->dispatch('toast', message: 'Link aktualisiert', type: 'success');
        $this->closeModal();
    }

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

    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();
    }
}
