<?php

namespace App\Http\Controllers\Ranch;

use App\Http\Controllers\Controller;
use App\Services\DatabaseBackupService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class RanchDatabaseBackupController extends Controller
{
    public function index(DatabaseBackupService $service): JsonResponse
    {
        return response()->json([
            'data' => [
                'backups' => $service->listBackups(),
                'retention_days' => (int) config('ranch.backup.retention_days', 14),
                'gzip' => (bool) config('ranch.backup.gzip', true),
            ],
        ]);
    }

    public function download(Request $request, DatabaseBackupService $service): BinaryFileResponse|JsonResponse
    {
        try {
            $fresh = $request->boolean('fresh', ! $request->filled('file'));
            $backup = $service->resolveDownload(
                $request->query('file'),
                $fresh,
            );

            $mime = $backup['compressed']
                ? 'application/gzip'
                : 'application/sql';

            return response()->download(
                $backup['path'],
                $backup['filename'],
                ['Content-Type' => $mime],
            );
        } catch (\Throwable $e) {
            return response()->json([
                'message' => $e->getMessage(),
            ], 503);
        }
    }
}
