<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Jobs\GenerateReport;
use App\Models\Report;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

class ReportController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Report::query()->with('author:id,name,avatar');

        if ($f = $request->string('format')->toString()) $query->where('format', $f);
        if ($q = $request->string('q')->toString()) {
            $query->where(function ($w) use ($q) {
                $w->where('title', 'like', "%{$q}%")
                  ->orWhere('description', 'like', "%{$q}%");
            });
        }

        $perPage = min(100, max(10, (int) $request->integer('per_page', 50)));
        $rows = $query->orderByDesc('created_at')->paginate($perPage);

        return response()->json([
            'data' => $rows->items(),
            'meta' => [
                'current_page' => $rows->currentPage(),
                'last_page' => $rows->lastPage(),
                'total' => $rows->total(),
            ],
            'summary' => [
                'total' => Report::count(),
                'auto_generated' => Report::where('auto_generated', true)->count(),
                'pdf' => Report::where('format', 'PDF')->count(),
                'downloads' => (int) Report::sum('downloads'),
            ],
        ]);
    }

    /**
     * Queue a report generation job. Reports can take seconds to minutes
     * for large date ranges, so we run them async.
     */
    public function generate(Request $request): JsonResponse
    {
        abort_unless($request->user()->role !== 'viewer', 403);

        $data = $request->validate([
            'type' => ['required', Rule::in(['uptime_sla', 'incident_analytics', 'server_performance', 'ssl_audit', 'security_audit', 'activity_audit'])],
            'period' => ['nullable', 'string', 'max:32'],
        ]);

        GenerateReport::dispatch($data['type'], $data['period'] ?? null, $request->user()->id);

        return response()->json([
            'queued' => true,
            'message' => 'Report queued. It will appear in the list when ready.',
        ]);
    }

    public function download(Request $request, Report $report)
    {
        abort_unless(Storage::disk('local')->exists($report->file_path), 404);

        $report->increment('downloads');

        return response()->stream(function () use ($report) {
            $stream = Storage::disk('local')->readStream($report->file_path);
            fpassthru($stream);
        }, 200, [
            'Content-Type' => $report->format === 'CSV' ? 'text/csv' : 'application/pdf',
            'Content-Disposition' => 'attachment; filename="' . basename($report->file_path) . '"',
            'Content-Length' => $report->file_size_bytes,
        ]);
    }

    public function destroy(Request $request, Report $report): JsonResponse
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        if (Storage::disk('local')->exists($report->file_path)) {
            Storage::disk('local')->delete($report->file_path);
        }
        $report->delete();
        return response()->json(['ok' => true]);
    }
}
