<?php

namespace App\Http\Controllers;

use App\Http\Requests\SiteExportRequest;
use App\Repositories\SiteExportRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Schema;

class SiteExportController extends Controller
{
    /**
     * List available tables with record counts
     */
    public function tables(SiteExportRequest $request, SiteExportRepository $repository): JsonResponse
    {
        $includeVehicles = $request->boolean('include_vehicles');

        return response()->json([
            'tables' => $repository->getTablesWithCounts($includeVehicles),
            'include_vehicles' => $includeVehicles,
        ]);
    }

    /**
     * Export paginated data for a specific table
     */
    public function data(SiteExportRequest $request, string $table, SiteExportRepository $repository): JsonResponse
    {
        $includeVehicles = $request->boolean('include_vehicles');

        if (!$repository->isTableAllowed($table, $includeVehicles)) {
            return response()->json([
                'error' => 'Table not allowed for export',
            ], 403);
        }

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

        $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'],
        ]);
    }
}
