/**
 * Admin Central API routes
 * Used by orchestration portal, token-aggregation, multi-chain-execution for:
 * - Appending audit entries (who asked what, when, outcome)
 * - Checking permissions (subjectId + permission)
 * - Querying audit log
 * Auth: X-Admin-Central-Key header (ADMIN_CENTRAL_API_KEY env)
 */

import { Router, Request, Response } from 'express';
import { requireAdminCentralKey } from '@/integration/api-gateway/middleware/admin-central-auth.middleware';
import { adminAuditService } from '@/core/admin/shared/admin-audit.service';
import { adminPermissionsService } from '@/core/admin/shared/admin-permissions.service';
import { AdminPermission } from '@/core/admin/shared/permissions.constants';

const router = Router();
router.use(requireAdminCentralKey);

/** POST /api/admin/central/audit - Append audit entry (from external admin services) */
router.post('/audit', async (req: Request, res: Response): Promise<void> => {
  try {
    const body = req.body as {
      employeeId: string;
      action: string;
      permission: string;
      resourceType: string;
      resourceId?: string;
      project?: string;
      service?: string;
      outcome?: string;
      beforeState?: Record<string, unknown>;
      afterState?: Record<string, unknown>;
      metadata?: Record<string, unknown>;
      ipAddress?: string;
      userAgent?: string;
    };

    if (!body?.employeeId || !body?.action || !body?.resourceType) {
      res.status(400).json({
        success: false,
        error: { code: 'VALIDATION_ERROR', message: 'employeeId, action, resourceType required' },
      });
      return;
    }

    await adminAuditService.logAction({
      employeeId: body.employeeId,
      action: body.action,
      permission: body.permission ?? 'admin:action',
      resourceType: body.resourceType,
      resourceId: body.resourceId,
      project: body.project,
      service: body.service,
      outcome: body.outcome,
      beforeState: body.beforeState,
      afterState: body.afterState,
      metadata: body.metadata,
      ipAddress: body.ipAddress ?? (req.ip || (req.headers['x-forwarded-for'] as string)?.split(',')[0]),
      userAgent: body.userAgent ?? (req.headers['user-agent'] as string),
    });

    res.status(201).json({ success: true });
  } catch (e) {
    res.status(500).json({
      success: false,
      error: { code: 'INTERNAL_ERROR', message: e instanceof Error ? e.message : 'Unknown error' },
    });
  }
});

/** GET /api/admin/central/audit - Query audit log */
router.get('/audit', async (req: Request, res: Response): Promise<void> => {
  try {
    const employeeId = req.query.employeeId as string | undefined;
    const resourceType = req.query.resourceType as string | undefined;
    const project = req.query.project as string | undefined;
    const service = req.query.service as string | undefined;
    const limit = Math.min(Number(req.query.limit) || 100, 500);

    const entries = await adminAuditService.getAuditLog(
      employeeId,
      resourceType,
      project,
      service,
      limit
    );
    res.json({ success: true, data: entries });
  } catch (e) {
    res.status(500).json({
      success: false,
      error: { code: 'INTERNAL_ERROR', message: e instanceof Error ? e.message : 'Unknown error' },
    });
  }
});

/** POST /api/admin/central/permission-check - Check if subject has permission */
router.post('/permission-check', async (req: Request, res: Response): Promise<void> => {
  try {
    const body = req.body as { subjectId: string; permission: string; resourceId?: string };
    if (!body?.subjectId || !body?.permission) {
      res.status(400).json({
        success: false,
        error: { code: 'VALIDATION_ERROR', message: 'subjectId and permission required' },
      });
      return;
    }

    const permission = body.permission as AdminPermission;
    const allowed = Object.values(AdminPermission).includes(permission)
      ? await adminPermissionsService.hasPermission(body.subjectId, permission)
      : false;

    res.json({ success: true, allowed });
  } catch (e) {
    res.status(500).json({
      success: false,
      error: { code: 'INTERNAL_ERROR', message: e instanceof Error ? e.message : 'Unknown error' },
    });
  }
});

export default router;
