<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Backup;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class BackupController extends Controller
{
    /**
     * Upload a backup from device
     */
    public function upload(Request $request): JsonResponse
    {
        $request->validate([
            'backup' => 'required|file|max:102400', // 100MB
            'device_id' => 'required|string',
        ]);

        $user = $request->user();
        if (!$user->hasModule('backup')) {
            return response()->json(['error' => 'Backup is not available on your plan'], 403);
        }

        $storageLimitBytes = ((int) $user->planLimit('storage_gb', 1)) * 1024 * 1024 * 1024;
        if (($user->storage_used_bytes + $request->file('backup')->getSize()) > $storageLimitBytes) {
            return response()->json(['error' => 'Storage limit reached for your plan'], 422);
        }

        $file = $request->file('backup');
        $fileName = 'backup_' . now()->format('Y-m-d_His') . '_' . Str::random(8) . '.sql';
        $path = $file->storeAs("backups/{$user->id}", $fileName, 'local');

        $backup = Backup::create([
            'user_id' => $user->id,
            'device_id' => $request->device_id,
            'type' => 'cloud',
            'file_name' => $fileName,
            'file_path' => $path,
            'file_size_bytes' => $file->getSize(),
            'status' => 'completed',
            'completed_at' => now(),
        ]);

        $user->increment('storage_used_bytes', $file->getSize());

        return response()->json(['backup_id' => $backup->id, 'file_name' => $fileName], 201);
    }

    /**
     * List user's cloud backups
     */
    public function index(Request $request): JsonResponse
    {
        if (!$request->user()->hasModule('backup')) {
            return response()->json(['error' => 'Backup is not available on your plan'], 403);
        }

        $backups = Backup::where('user_id', $request->user()->id)
            ->latest()
            ->limit(20)
            ->get(['id', 'file_name', 'file_size_bytes', 'status', 'completed_at', 'created_at']);

        return response()->json(['backups' => $backups]);
    }

    /**
     * Download a specific backup
     */
    public function download(Request $request, string $backupId): \Symfony\Component\HttpFoundation\BinaryFileResponse
    {
        $backup = Backup::where('user_id', $request->user()->id)->findOrFail($backupId);
        abort_unless(Storage::disk('local')->exists($backup->file_path), 404, 'Backup file not found');
        return response()->download(Storage::disk('local')->path($backup->file_path), $backup->file_name);
    }

    /**
     * Delete a specific backup
     */
    public function destroy(Request $request, string $backupId): JsonResponse
    {
        $backup = Backup::where('user_id', $request->user()->id)->findOrFail($backupId);
        if (Storage::disk('local')->exists($backup->file_path)) {
            Storage::disk('local')->delete($backup->file_path);
        }
        $request->user()->decrement('storage_used_bytes', $backup->file_size_bytes);
        $backup->delete();
        return response()->json(['message' => 'Backup deleted.']);
    }
}
