/**
 * Admin audit endpoint — read-only SQL queries for dev/debugging.
 *
 * Auth : header `X-Admin-Audit-Token` comparé à process.env.ADMIN_AUDIT_TOKEN.
 * Sécurité :
 *   - Token obligatoire (pas de fallback)
 *   - Seules les queries commençant par SELECT ou WITH (CTE) sont acceptées
 *   - Pas de DDL, DML, ou fonctions/procédures
 *   - Timeout 10s par query
 *   - Limite 10000 rows par query
 *
 * Endpoints :
 *   POST /api/admin-audit/query    — body { sql: string } → { rows, row_count, duration_ms }
 *   POST /api/admin-audit/batch    — body { queries: string[] } → { results: [...] }
 *     (évite le rate-limit 429 de TigerProtect sur o2switch — 1 HTTP call = N résultats)
 *   GET  /api/admin-audit/ping     — health check token
 */
import { Router, Response, Request } from 'express';
import { AppDataSource } from '../../config/database';

const router = Router();

const MAX_ROWS = 10000;
const QUERY_TIMEOUT_MS = 10000;
const MAX_BATCH_SIZE = 20;

/** Middleware d'auth par token header (secret partagé). Constant-time compare. */
function requireAuditToken(req: Request, res: Response, next: () => void) {
  const provided = req.header('X-Admin-Audit-Token') ?? '';
  const expected = process.env.ADMIN_AUDIT_TOKEN ?? '';
  if (!expected) {
    return res.status(503).json({ error: 'ADMIN_AUDIT_TOKEN not configured on server' });
  }
  if (provided.length !== expected.length) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  let diff = 0;
  for (let i = 0; i < expected.length; i++) diff |= provided.charCodeAt(i) ^ expected.charCodeAt(i);
  if (diff !== 0) return res.status(401).json({ error: 'Unauthorized' });
  next();
}

router.use(requireAuditToken);

/** Valide qu'une SQL est read-only (SELECT/WITH) et sans mots-clés DDL/DML. */
function validateReadOnlySql(sql: string): string | null {
  const firstWord = sql.replace(/^\s*(\/\*[\s\S]*?\*\/|--[^\n]*\n)*\s*/, '').slice(0, 10).toUpperCase();
  if (!firstWord.startsWith('SELECT') && !firstWord.startsWith('WITH')) {
    return 'Only SELECT/WITH queries allowed';
  }
  const forbidden = /\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE|GRANT|REVOKE|COPY|CALL)\b/i;
  if (forbidden.test(sql)) return 'Forbidden keyword detected';
  return null;
}

/** Exécute une query via un QueryRunner dédié (timeout isolé). */
async function executeReadOnly(sql: string): Promise<{
  rows: any[]; row_count: number; truncated: boolean; duration_ms: number; error?: string;
}> {
  const t0 = Date.now();
  const qr = AppDataSource.createQueryRunner();
  try {
    await qr.connect();
    await qr.query(`SET statement_timeout = ${QUERY_TIMEOUT_MS}`);
    const rows = await qr.query(sql);
    const duration_ms = Date.now() - t0;
    const truncated = Array.isArray(rows) && rows.length > MAX_ROWS;
    return {
      rows: truncated ? rows.slice(0, MAX_ROWS) : (Array.isArray(rows) ? rows : []),
      row_count: Array.isArray(rows) ? rows.length : 0,
      truncated,
      duration_ms,
    };
  } catch (err: any) {
    return {
      rows: [], row_count: 0, truncated: false,
      duration_ms: Date.now() - t0,
      error: String(err?.message ?? err).slice(0, 500),
    };
  } finally {
    await qr.release();
  }
}

/** POST /api/admin-audit/query — body { sql: string } → rows. */
router.post('/query', async (req: Request, res: Response) => {
  const sql = (req.body?.sql ?? '').trim();
  if (!sql) return res.status(400).json({ error: 'Missing sql' });
  const validationError = validateReadOnlySql(sql);
  if (validationError) return res.status(400).json({ error: validationError });
  const result = await executeReadOnly(sql);
  if (result.error) return res.status(400).json({ error: result.error });
  return res.json(result);
});

/**
 * POST /api/admin-audit/batch — body { queries: string[] } → results.
 * Élimine le rate-limit 429 de TigerProtect : 1 HTTP call = N résultats.
 * Chaque query est validée individuellement (read-only). Si 1 échoue, les autres continuent.
 */
router.post('/batch', async (req: Request, res: Response) => {
  const queries = req.body?.queries;
  if (!Array.isArray(queries) || queries.length === 0) {
    return res.status(400).json({ error: 'Missing or invalid queries (array)' });
  }
  if (queries.length > MAX_BATCH_SIZE) {
    return res.status(400).json({ error: `Batch too large, max ${MAX_BATCH_SIZE}` });
  }
  const t0 = Date.now();
  const results: Array<{ sql: string } & Awaited<ReturnType<typeof executeReadOnly>>> = [];
  for (const rawSql of queries) {
    const sql = String(rawSql ?? '').trim();
    if (!sql) {
      results.push({ sql, rows: [], row_count: 0, truncated: false, duration_ms: 0, error: 'Empty SQL' });
      continue;
    }
    const validationError = validateReadOnlySql(sql);
    if (validationError) {
      results.push({ sql, rows: [], row_count: 0, truncated: false, duration_ms: 0, error: validationError });
      continue;
    }
    const r = await executeReadOnly(sql);
    results.push({ sql, ...r });
  }
  return res.json({ results, total_duration_ms: Date.now() - t0, count: results.length });
});

/** GET /api/admin-audit/ping — teste que l'endpoint est up et que le token est OK. */
router.get('/ping', (_req: Request, res: Response) => {
  res.json({ ok: true, ts: new Date().toISOString() });
});

/**
 * POST /api/admin-audit/run-task — body { task: string }
 * Tâches admin ponctuelles idempotentes (rétro-migrations data).
 *
 * Tâches supportées :
 *   - "regen-auto-pois" : pour chaque joueur non-NPC avec territoire,
 *     appelle DealershipService.autoGenerateForPlayer + CasinoService.autoGenerateForPlayer
 *     + génère un weapons_cache POI si absent (0.5-1 km du territoire).
 */
router.post('/run-task', async (req: Request, res: Response) => {
  const task = String(req.body?.task ?? '').trim();
  if (!task) return res.status(400).json({ error: 'Missing task' });

  if (task === 'regen-auto-pois') {
    try {
      const { Player } = await import('../../models/Player');
      const { Warehouse } = await import('../../models/Warehouse');
      const { POI } = await import('../../models/POI');
      const { DealershipService } = await import('../../services/dealership.service');
      const { CasinoService } = await import('../../services/casino.service');
      const playerRepo = AppDataSource.getRepository(Player);
      const whRepo = AppDataSource.getRepository(Warehouse);
      const poiRepo = AppDataSource.getRepository(POI);

      const players = await playerRepo
        .createQueryBuilder('p')
        .where('p.is_npc = false')
        .andWhere('p.start_lat IS NOT NULL')
        .andWhere('p.start_lon IS NOT NULL')
        .andWhere('p.selected_zone_id IS NOT NULL')
        .getMany();

      let dealershipCreated = 0, casinoCreated = 0, weaponsCacheCreated = 0, skipped = 0;

      for (const player of players) {
        // Concessionnaire
        try {
          const d = await DealershipService.autoGenerateForPlayer(player.id);
          if (d && !(d as any).existedBefore) dealershipCreated++;
        } catch (e) {
          // Ignore errors per player (continue with others)
        }
        // Casino
        try {
          const c = await CasinoService.autoGenerateForPlayer(player.id);
          if (c) casinoCreated++;
        } catch (e) {
          // Ignore
        }
        // Weapons_cache (warehouse + POI)
        try {
          const existing = await whRepo.findOne({
            where: { player_id: player.id, type: 'weapons_cache' as any },
          });
          if (!existing) {
            const lat0 = Number(player.start_lat);
            const lon0 = Number(player.start_lon);
            const angle = Math.random() * 2 * Math.PI;
            const distanceKm = 0.5 + Math.random() * 0.5;
            const latOffset = (distanceKm / 111) * Math.cos(angle);
            const lonOffset = (distanceKm / (111 * Math.cos(lat0 * Math.PI / 180))) * Math.sin(angle);
            const lat = lat0 + latOffset;
            const lon = lon0 + lonOffset;
            const zoneId = player.selected_zone_id!;
            const wh = whRepo.create({
              player_id: player.id, type: 'weapons_cache' as any,
              name: 'Cache d\'armes', zone_id: zoneId,
              location_lat: lat, location_lon: lon,
              storage_capacity_kg: 100, current_stock_kg: 0,
            } as any);
            const savedWh = await whRepo.save(wh as any);
            await poiRepo.save(poiRepo.create({
              zone_id: zoneId,
              type: 'warehouse' as any,
              name: 'Cache d\'armes',
              location_lat: lat, location_lon: lon,
              entity_id: (savedWh as any).id,
              icon: 'weapons_cache',
              is_visible: true,
            } as any));
            weaponsCacheCreated++;
          } else {
            skipped++;
          }
        } catch (e) {
          // Ignore
        }
      }

      return res.json({
        task: 'regen-auto-pois',
        total_players: players.length,
        dealership_created: dealershipCreated,
        casino_created: casinoCreated,
        weapons_cache_created: weaponsCacheCreated,
        weapons_cache_skipped: skipped,
      });
    } catch (err: any) {
      return res.status(500).json({ error: String(err?.message ?? err).slice(0, 500) });
    }
  }

  return res.status(400).json({ error: `Unknown task: ${task}` });
});

export default router;
