<?php

namespace App\Http\Controllers;

use App\Http\Requests\SiteExportRequest;
use App\Repositories\SiteExportRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\Response;

class SiteExportController extends Controller
{
    /**
     * List available tables with record counts for the selected modules
     */
    public function tables(SiteExportRequest $request, SiteExportRepository $repository): JsonResponse
    {
        $modules = $request->input('modules', []);

        return response()->json([
            'modules' => $modules ?: $repository->moduleKeys(),
            'tables' => $repository->getTablesWithCounts($modules),
        ]);
    }

    /**
     * Export paginated data for a specific table
     */
    public function data(SiteExportRequest $request, string $table, SiteExportRepository $repository): JsonResponse
    {
        if (!$repository->isTableAllowed($table)) {
            return response()->json([
                'error' => 'Table not allowed for export',
            ], 403);
        }

        if (!Schema::hasTable($table)) {
            return response()->json([
                'error' => 'Table does not exist',
            ], 404);
        }

        if ($repository->exportSource($table) === null) {
            return response()->json([
                'error' => 'Table holds personal data and its redacted view is missing',
            ], 403);
        }

        $page = $request->integer('page', 1);

        // Special handling for settings table - decrypt secrets and re-encrypt with token
        if ($table === 'settings') {
            $result = $repository->getSettingsData(
                $request->getEncryptionKey(),
                $page
            );
        } else {
            $result = $repository->getTableData($table, $page);
        }

        return response()->json([
            'table' => $table,
            'data' => $result['data'],
            'pagination' => $result['pagination'],
        ]);
    }

    /**
     * List the tenant's media files (path + size) available for download
     */
    public function files(SiteExportRequest $request, SiteExportRepository $repository): JsonResponse
    {
        return response()->json([
            'files' => $repository->getMediaFiles(),
        ]);
    }

    /**
     * Stream the contents of a single media file
     */
    public function file(SiteExportRequest $request, SiteExportRepository $repository): Response
    {
        $path = (string) $request->input('path');

        if (!$repository->isMediaFileAllowed($path)) {
            return response()->json([
                'error' => 'File not allowed for export',
            ], 403);
        }

        $disk = Storage::disk($repository->mediaDisk());

        if (!$disk->exists($path)) {
            return response()->json([
                'error' => 'File does not exist',
            ], 404);
        }

        return $disk->response($path);
    }
}
