<?php

declare(strict_types=1);

namespace App\Modules\Developer;

use App\Core\BaseController;
use App\Core\Request;

/**
 * DeveloperController — Developer Console Module
 *
 * Thin controller — all business logic lives in services.
 * Each method: validate → call service → render or JSON.
 *
 * Routes:
 *   GET  /app/developer                   → index()            (Dashboard)
 *   GET  /app/developer/database          → database()         (Database Overview)
 *   GET  /app/developer/schema            → schema()           (Schema Docs)
 *   GET  /app/developer/supabase          → supabase()         (Supabase Inspector)
 *   POST /app/developer/supabase/test     → testSupabaseConnection()
 *   GET  /app/developer/inspector         → inspector()        (DB Inspector)
 *   GET  /app/developer/mapping           → mappingDoc()       (Type Mapping Reference)
 *   GET  /app/developer/sync              → sync()             (Sync Dashboard)
 *   GET  /app/developer/sync/log          → syncLog()          (Sync History)
 *   POST /app/developer/sync/compare      → syncCompare()
 *   POST /app/developer/sync/dry-run      → syncDryRun()
 *   POST /app/developer/sync/push         → syncPush()
 *   POST /app/developer/sync/verify       → syncVerify()
 *   POST /app/developer/sync/preview      → syncPreview()
 *   POST /app/developer/sync/log/clear    → syncLogClear()
 *   GET  /app/developer/health            → health()           (System Health DX003)
 *   GET  /app/developer/info              → info()             (App Info / About DX003)
 *   GET  /app/developer/logs              → logs()             (Log Center DX003)
 *   POST /app/developer/logs/clear        → logClear()         (Clear Logs DX003)
 *   GET  /app/developer/logs/download     → logDownload()      (Download Log DX003)
 *
 * @package Inveetaire
 * @ref     DX001, DX002A, DX002B, DX003
 */
class DeveloperController extends BaseController
{
    protected string $layout = 'developer';

    private DeveloperService       $service;
    private MySqlInspectorService  $mysqlInspector;
    private SupabaseService        $supabaseService;
    private SchemaReaderService    $schemaReader;
    private SynchronizationService $syncService;
    private SystemHealthService    $healthService;
    private LogManagerService      $logManager;

    public function __construct()
    {
        parent::__construct();
        $this->service         = new DeveloperService();
        $this->mysqlInspector  = new MySqlInspectorService();
        $this->supabaseService = new SupabaseService();
        $this->schemaReader    = new SchemaReaderService();
        $this->syncService     = new SynchronizationService();
        $this->healthService   = new SystemHealthService();
        $this->logManager      = new LogManagerService();
    }

    // ─────────────────────────────────────────────────────────────────────────
    // DX001 & DX003 — Dashboard & Core Routes
    // ─────────────────────────────────────────────────────────────────────────

    public function index(Request $request): void
    {
        $mysqlData    = $this->mysqlInspector->inspect();
        $supabaseData = $this->supabaseService->getProjectInfo();
        $syncStatus   = $this->syncService->getStatus();
        $health       = $this->healthService->inspectHealth();
        $dbOverview   = $this->service->getDatabaseOverview();

        $this->render('developer/console', [
            'title'          => 'Developer Dashboard',
            'active_page'    => 'console',
            'mysql_data'     => $mysqlData,
            'supabase_info'  => $supabaseData,
            'sync_status'    => $syncStatus,
            'health'         => $health,
            'db_overview'    => $dbOverview,
            'app_info'       => $this->service->getApplicationInfo(),
            'total_routes'   => $this->service->getTotalRoutes(),
            'total_modules'  => $this->service->getTotalModules(),
            'storage_usage'  => $this->service->getStorageUsage(),
            'doc_status'     => $this->service->getDocumentationStatus(),
        ]);
    }

    public function database(Request $request): void
    {
        $mysqlData    = $this->mysqlInspector->inspect();
        $supabaseData = $this->supabaseService->getProjectInfo();
        $dbOverview   = $this->service->getDatabaseOverview();

        $this->render('developer/database', [
            'title'         => 'Database — Developer Console',
            'active_page'   => 'database',
            'mysql_info'    => $mysqlData,
            'supabase_info' => $supabaseData,
            'db_overview'   => $dbOverview,
            'db_info'       => $mysqlData, // backward compat
        ]);
    }

    public function schema(Request $request): void
    {
        $this->render('developer/schema', [
            'title'       => 'Schema Documentation — Developer Console',
            'active_page' => 'schema',
            'doc_status'  => $this->service->getDocumentationStatus(),
        ]);
    }

    // ─────────────────────────────────────────────────────────────────────────
    // DX002A — Supabase Inspector Routes
    // ─────────────────────────────────────────────────────────────────────────

    public function supabase(Request $request): void
    {
        $this->render('developer/supabase', [
            'title'         => 'Supabase Mirror — Developer Console',
            'active_page'   => 'supabase',
            'project_info'  => $this->supabaseService->getProjectInfo(),
            'config_status' => $this->supabaseService->getConfigStatus(),
            'schemas'       => $this->supabaseService->isConfigured()
                ? $this->supabaseService->getAvailableSchemas() : [],
            'sync_status'   => $this->syncService->getStatus(),
        ]);
    }

    public function inspector(Request $request): void
    {
        $comparison  = $this->schemaReader->compareTableLists();
        $mysqlTables = $this->schemaReader->getMysqlTables();

        $this->render('developer/inspector', [
            'title'         => 'Inspector — Developer Console',
            'active_page'   => 'inspector',
            'mysql_data'    => $this->mysqlInspector->inspect(),
            'supabase_info' => $this->supabaseService->getProjectInfo(),
            'comparison'    => $comparison,
            'mysql_tables'  => $mysqlTables,
        ]);
    }

    public function mappingDoc(Request $request): void
    {
        $this->render('developer/mapping', [
            'title'       => 'Type Mapping — Developer Console',
            'active_page' => 'mapping',
        ]);
    }

    public function testSupabaseConnection(Request $request): void
    {
        $this->respondJson($this->supabaseService->testConnection());
    }

    // ─────────────────────────────────────────────────────────────────────────
    // DX002B — Synchronization Routes
    // ─────────────────────────────────────────────────────────────────────────

    public function sync(Request $request): void
    {
        $this->render('developer/sync', [
            'title'        => 'Synchronization — Developer Console',
            'active_page'  => 'sync',
            'sync_status'  => $this->syncService->getStatus(),
            'recent_logs'  => $this->syncService->getLogs(5),
            'supabase_info'=> $this->supabaseService->getProjectInfo(),
        ]);
    }

    public function syncLog(Request $request): void
    {
        $this->render('developer/sync_log', [
            'title'       => 'Sync Log — Developer Console',
            'active_page' => 'sync_log',
            'logs'        => $this->syncService->getLogs(100),
        ]);
    }

    public function syncCompare(Request $request): void
    {
        $result = $this->syncService->compare();
        $this->respondJson($result);
    }

    public function syncDryRun(Request $request): void
    {
        $username = $this->getCurrentUsername();
        $result   = $this->syncService->dryRun($username);
        $this->respondJson($result);
    }

    public function syncPush(Request $request): void
    {
        $body      = json_decode((string)file_get_contents('php://input'), true) ?? [];
        $confirmed = (bool)($body['confirmed'] ?? false);
        $mode      = in_array($body['mode'] ?? '', ['full', 'incremental'], true)
            ? ($body['mode'] ?? 'incremental') : 'incremental';

        if (!$confirmed) {
            $this->respondJson(['success' => false, 'error' => 'Push requires explicit confirmation.']);
            return;
        }

        $username = $this->getCurrentUsername();
        $result   = $this->syncService->push($confirmed, $mode, $username);
        $this->respondJson($result);
    }

    public function syncVerify(Request $request): void
    {
        $result = $this->syncService->verify();
        $this->respondJson($result);
    }

    public function syncPreview(Request $request): void
    {
        $body = json_decode((string)file_get_contents('php://input'), true) ?? [];
        $mode = in_array($body['mode'] ?? '', ['full', 'incremental'], true)
            ? ($body['mode'] ?? 'incremental') : 'incremental';

        $result = $this->syncService->generatePreview($mode);
        $this->respondJson($result);
    }

    public function syncLogClear(Request $request): void
    {
        $this->syncService->clearLogs();
        $this->respondJson(['success' => true, 'message' => 'Sync log cleared.']);
    }

    // ─────────────────────────────────────────────────────────────────────────
    // DX003 — System Health, App Information & Log Center Routes
    // ─────────────────────────────────────────────────────────────────────────

    /**
     * System Health Diagnostics page (DX003 Feature 2).
     */
    public function health(Request $request): void
    {
        $this->render('developer/health', [
            'title'       => 'System Health — Developer Console',
            'active_page' => 'health',
            'health_data' => $this->healthService->inspectHealth(),
        ]);
    }

    /**
     * Application Metadata & About page (DX003 Feature 3).
     */
    public function info(Request $request): void
    {
        $this->render('developer/info', [
            'title'       => 'Application Information — Developer Console',
            'active_page' => 'info',
            'app_info'    => $this->service->getApplicationInfo(),
        ]);
    }

    /**
     * Centralized Log Center page (DX003 Feature 4).
     */
    public function logs(Request $request): void
    {
        $type = (string)($request->getQueryParams()['type'] ?? 'all');
        if (!in_array($type, ['all', 'sync', 'app', 'php_error'], true)) {
            $type = 'all';
        }

        $this->render('developer/logs', [
            'title'        => 'Log Center — Developer Console',
            'active_page'  => 'logs',
            'current_type' => $type,
            'logs'         => $this->logManager->getLogs($type, 100),
            'log_files'    => $this->logManager->getLogFilesList(),
        ]);
    }

    /**
     * AJAX POST: Clear log center logs (DX003 Feature 4).
     */
    public function logClear(Request $request): void
    {
        $body = json_decode((string)file_get_contents('php://input'), true) ?? [];
        $type = (string)($body['type'] ?? 'all');

        $success = $this->logManager->clearLog($type);
        $this->respondJson([
            'success' => $success,
            'message' => $success ? "Log '{$type}' cleared successfully." : "Failed to clear log.",
        ]);
    }

    /**
     * GET: Secure log file download (DX003 Feature 4).
     */
    public function logDownload(Request $request): void
    {
        $type = (string)($request->getQueryParams()['type'] ?? 'all');
        $filePath = $this->logManager->getDownloadPath($type);

        if (!$filePath || !file_exists($filePath)) {
            http_response_code(404);
            echo "Log file not found.";
            exit;
        }

        $filename = basename($filePath);
        header('Content-Type: text/plain; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Private Helpers
    // ─────────────────────────────────────────────────────────────────────────

    private function respondJson(array $data): void
    {
        header('Content-Type: application/json; charset=utf-8');
        // SECURITY: strip any credential-adjacent keys
        unset($data['service_role_key'], $data['access_token'], $data['anon_key']);
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    private function getCurrentUsername(): string
    {
        return (string)($_SESSION['user_name'] ?? $_SESSION['display_name'] ?? 'super_admin');
    }
}
