<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Upload;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

final class UploadModerationController extends Controller
{
    public function pending(): JsonResponse
    {
        $uploads = Upload::query()
            ->where('status', 'draft')
            ->where('moderation_status', 'pending')
            ->orderBy('created_at')
            ->get([
                'id',
                'user_id',
                'type',
                'status',
                'processing_state',
                'title',
                'preview_path',
                'created_at',
                'moderation_status',
            ]);

        return response()->json([
            'data' => $uploads,
        ], Response::HTTP_OK);
    }

    public function approve(string $id, Request $request): JsonResponse
    {
        $upload = Upload::query()->find($id);

        if (! $upload) {
            return response()->json(['message' => 'Upload not found.'], Response::HTTP_NOT_FOUND);
        }

        $upload->moderation_status = 'approved';
        $upload->moderated_at = now();
        $upload->moderated_by = (int) $request->user()->id;
        $upload->moderation_note = $request->input('note');
        $upload->save();

        return response()->json([
            'success' => true,
            'id' => (string) $upload->id,
            'moderation_status' => (string) $upload->moderation_status,
        ], Response::HTTP_OK);
    }

    public function reject(string $id, Request $request): JsonResponse
    {
        $upload = Upload::query()->find($id);

        if (! $upload) {
            return response()->json(['message' => 'Upload not found.'], Response::HTTP_NOT_FOUND);
        }

        $upload->moderation_status = 'rejected';
        $upload->status = 'rejected';
        $upload->processing_state = 'rejected';
        $upload->moderated_at = now();
        $upload->moderated_by = (int) $request->user()->id;
        $upload->moderation_note = (string) $request->input('note', '');
        $upload->save();

        return response()->json([
            'success' => true,
            'id' => (string) $upload->id,
            'status' => (string) $upload->status,
            'processing_state' => (string) $upload->processing_state,
            'moderation_status' => (string) $upload->moderation_status,
        ], Response::HTTP_OK);
    }
}
