<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Marketplace;

use App\Http\Controllers\Controller;
use App\Models\MarketplaceItem;
use App\Models\MarketplacePurchase;
use App\Services\Marketplace\MarketplacePurchaseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MarketplacePurchaseController extends Controller
{
    public function __construct(private readonly MarketplacePurchaseService $service) {}

    public function purchase(Request $request, string $id): JsonResponse
    {
        $user = $request->user();
        if (! $user) abort(401);

        $item = MarketplaceItem::where('id', $id)->where('status', 'approved')->firstOrFail();

        $data = $request->validate([
            'payment_id' => ['nullable', 'uuid'],
        ]);

        if (! $item->is_free && empty($data['payment_id'])) {
            // For paid items, require a payment_id from the payment module.
            return response()->json(['error' => 'PAYMENT_REQUIRED'], 422);
        }

        $purchase = $this->service->purchase($item, $user->id, $data['payment_id'] ?? null);
        return response()->json(['data' => $purchase], 201);
    }

    public function myPurchases(Request $request): JsonResponse
    {
        $user = $request->user();
        if (! $user) abort(401);

        $list = MarketplacePurchase::with('item:id,slug,name,type,screenshot_url,version')
            ->where('user_id', $user->id)
            ->orderByDesc('purchased_at')
            ->paginate(20);

        return response()->json(['data' => $list]);
    }
}
