<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Release;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ReleaseController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json(['data' => Release::query()->with('product')->latest('published_at')->paginate()]);
    }

    public function store(Request $request): JsonResponse
    {
        $payload = $request->validate([
            'product_id' => ['required', 'uuid', 'exists:products,id'],
            'version' => ['required', 'string', 'max:80'],
            'channel' => ['sometimes', 'string', 'max:60'],
            'file_url' => ['required', 'url'],
            'sha256' => ['nullable', 'string', 'size:64'],
            'min_version' => ['nullable', 'string', 'max:80'],
            'is_required' => ['sometimes', 'boolean'],
            'published_at' => ['nullable', 'date'],
            'metadata' => ['sometimes', 'array'],
        ]);

        $payload['published_at'] ??= now();
        $release = Release::query()->create($payload);

        return response()->json(['data' => $release->load('product')], 201);
    }

    public function show(Release $release): JsonResponse
    {
        return response()->json(['data' => $release->load('product')]);
    }

    public function update(Request $request, Release $release): JsonResponse
    {
        $release->update($request->validate([
            'version' => ['sometimes', 'string', 'max:80'],
            'channel' => ['sometimes', 'string', 'max:60'],
            'file_url' => ['sometimes', 'url'],
            'sha256' => ['nullable', 'string', 'size:64'],
            'min_version' => ['nullable', 'string', 'max:80'],
            'is_required' => ['sometimes', 'boolean'],
            'published_at' => ['nullable', 'date'],
            'metadata' => ['sometimes', 'array'],
        ]));

        return response()->json(['data' => $release->refresh()->load('product')]);
    }

    public function latest(Request $request, Product $product): JsonResponse
    {
        $channel = $request->query('channel', 'stable');
        $release = $product->releases()
            ->where('channel', $channel)
            ->whereNotNull('published_at')
            ->orderByDesc('published_at')
            ->orderByDesc('version')
            ->firstOrFail();

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