<?php

namespace App\Http\Controllers\Api\V1;

use App\Domains\Api\Resources\LinkResource;
use App\Domains\Link\Actions\CreateLink;
use App\Domains\Link\Actions\DeleteLink;
use App\Domains\Link\Models\Link;
use App\Domains\Workspace\Models\Workspace;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;

class LinkController extends Controller
{
    public function index(Request $request, string $workspaceUlid): AnonymousResourceCollection
    {
        $workspace = Workspace::where('ulid', $workspaceUlid)->firstOrFail();
        $this->authorize('view', $workspace);

        $links = $workspace->links()->latest()->paginate(50);

        return LinkResource::collection($links);
    }

    public function store(Request $request, string $workspaceUlid, CreateLink $action): JsonResponse
    {
        $workspace = Workspace::where('ulid', $workspaceUlid)->firstOrFail();
        $this->authorize('update', $workspace);

        $validated = $request->validate([
            'target_url' => 'required|url:http,https|max:2048',
            'slug' => 'nullable|string|max:64|alpha_dash',
            'title' => 'nullable|string|max:255',
            'tags' => 'nullable|array',
            'tags.*' => 'string|max:64',
        ]);

        $link = $action->handle($workspace, $request->user(), $validated);

        return (new LinkResource($link))
            ->response()
            ->setStatusCode(201);
    }

    public function destroy(Request $request, string $workspaceUlid, string $linkUlid, DeleteLink $action): Response
    {
        $workspace = Workspace::where('ulid', $workspaceUlid)->firstOrFail();
        $this->authorize('update', $workspace);

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

        $action->handle($link);

        return response()->noContent();
    }
}
