<?php

namespace App\Http\Controllers\Admin;

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

class ChangelogAdminController extends Controller
{
    public function index(): View
    {
        return view('admin.changelog', [
            'entries' => ChangelogEntry::query()->with('product')->latest('published_at')->paginate(20),
            'products' => Product::query()->where('status', 'active')->orderBy('name')->get(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $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();
        ChangelogEntry::query()->create($payload);

        return back()->with('status', 'Changelog dibuat.');
    }

    public function update(Request $request, ChangelogEntry $changelogEntry): RedirectResponse
    {
        $changelogEntry->update($request->validate([
            'version' => ['required', 'string', 'max:80'],
            'title' => ['required', 'string', 'max:180'],
            'body' => ['required', 'string'],
            'published_at' => ['nullable', 'date'],
        ]));

        return back()->with('status', 'Changelog diperbarui.');
    }

    public function destroy(ChangelogEntry $changelogEntry): RedirectResponse
    {
        $changelogEntry->delete();

        return back()->with('status', 'Changelog dihapus.');
    }
}
