<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\NovaCards;

use App\Jobs\UpdateNovaCardStatsJob;
use App\Events\NovaCards\NovaCardDownloaded;
use App\Events\NovaCards\NovaCardShared;
use App\Http\Controllers\Controller;
use App\Models\NovaCard;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NovaCardEngagementController extends Controller
{
    public function share(Request $request, int $id): JsonResponse
    {
        $card = $this->card($request, $id);
        $card->increment('shares_count');
        $card->refresh();
        UpdateNovaCardStatsJob::dispatch($card->id);

        event(new NovaCardShared($card, $request->user()?->id));

        return response()->json([
            'ok' => true,
            'shares_count' => (int) $card->shares_count,
        ]);
    }

    public function download(Request $request, int $id): JsonResponse
    {
        $card = $this->card($request, $id);
        abort_unless($card->allow_download && $card->previewUrl() !== null, 404);

        $card->increment('downloads_count');
        $card->refresh();
        UpdateNovaCardStatsJob::dispatch($card->id);

        event(new NovaCardDownloaded($card, $request->user()?->id));

        return response()->json([
            'ok' => true,
            'downloads_count' => (int) $card->downloads_count,
            'download_url' => $card->previewUrl(),
        ]);
    }

    private function card(Request $request, int $id): NovaCard
    {
        $card = NovaCard::query()
            ->with(['user.profile', 'category', 'template', 'backgroundImage', 'tags'])
            ->published()
            ->findOrFail($id);

        abort_unless($card->canBeViewedBy($request->user()), 404);

        return $card;
    }
}
