<?php

namespace App\Http\Controllers\Admin;

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

class ReleaseAdminController extends Controller
{
    public function index(): View
    {
        return view('admin.releases', [
            'releases' => Release::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'],
            'channel' => ['required', 'string', 'max:60'],
            'file_url' => ['required', 'url'],
            'sha256' => ['nullable', 'string', 'size:64'],
            'min_version' => ['nullable', 'string', 'max:80'],
            'is_required' => ['nullable', 'boolean'],
            'published_at' => ['nullable', 'date'],
        ]);

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

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

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

        $payload['is_required'] = (bool) ($payload['is_required'] ?? false);
        $release->update($payload);

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

    public function destroy(Release $release): RedirectResponse
    {
        $release->delete();

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