<?php

namespace App\Http\Controllers\Api;

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

class ChangelogController extends Controller
{
    public function index(Product $product): JsonResponse
    {
        return response()->json([
            'data' => $product->changelogEntries()->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'],
            'title' => ['required', 'string', 'max:180'],
            'body' => ['required', 'string'],
            'published_at' => ['nullable', 'date'],
        ]);

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

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