import { INestApplication, ValidationPipe } from '@nestjs/common';
import cookieParser from 'cookie-parser';
import { ApiResponseInterceptor } from './common/interceptors/api-response.interceptor';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';

function normalizeOrigin(origin: string): string {
  return origin.trim().replace(/\/+$/, '');
}

function buildCorsOriginValidator() {
  const rawList = [process.env.FRONTEND_URL, process.env.CORS_ORIGINS, process.env.WEB_ORIGIN]
    .filter((v): v is string => Boolean(v && v.trim()))
    .flatMap((v) => v.split(','))
    .map(normalizeOrigin)
    .filter(Boolean);

  const allowedOrigins = new Set(rawList);
  const patternStr = process.env.CORS_ORIGIN_PATTERN?.trim();
  const originPattern = patternStr ? new RegExp(patternStr) : null;

  return (requestOrigin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {
    if (!requestOrigin) {
      return callback(null, true);
    }

    const normalized = normalizeOrigin(requestOrigin);
    if (allowedOrigins.has(normalized) || (originPattern && originPattern.test(normalized))) {
      return callback(null, true);
    }

    return callback(null, false);
  };
}

export function configureApp(app: INestApplication) {
  const http = app.getHttpAdapter().getInstance();
  http.disable('x-powered-by');
  const proxyHops = Number(process.env.TRUST_PROXY);
  if (Number.isInteger(proxyHops) && proxyHops > 0) http.set('trust proxy', proxyHops);

  app.use((_req: unknown, res: { setHeader: (k: string, v: string) => void }, next: () => void) => {
    res.setHeader('X-Content-Type-Options', 'nosniff');
    res.setHeader('X-Frame-Options', 'DENY');
    res.setHeader('Referrer-Policy', 'no-referrer');
    res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
    res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
    res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
    res.setHeader('Pragma', 'no-cache');
    if (process.env.NODE_ENV === 'production') {
      res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
    }
    next();
  });
  app.use(cookieParser());

  // CSRF Defense-in-depth: check Origin / Referer on state-modifying requests with cookie authentication
  app.use((req: any, res: any, next: () => void) => {
    const method = req.method?.toUpperCase();
    const isStateChanging = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(method);
    const hasAuthCookie = Boolean(req.cookies?.['__Host-tcx_token'] || req.cookies?.['tcx_token']);

    if (isStateChanging && hasAuthCookie) {
      const originHeader = req.headers?.['origin'] as string | undefined;
      const refererHeader = req.headers?.['referer'] as string | undefined;
      let requestOrigin = originHeader ? normalizeOrigin(originHeader) : undefined;
      if (!requestOrigin && refererHeader) {
        try {
          requestOrigin = normalizeOrigin(new URL(refererHeader).origin);
        } catch {
          // invalid referer format
        }
      }

      if (requestOrigin) {
        const rawList = [process.env.FRONTEND_URL, process.env.CORS_ORIGINS, process.env.WEB_ORIGIN]
          .filter((v): v is string => Boolean(v && v.trim()))
          .flatMap((v) => v.split(','))
          .map(normalizeOrigin)
          .filter(Boolean);
        const allowedOrigins = new Set(rawList);
        const patternStr = process.env.CORS_ORIGIN_PATTERN?.trim();
        const originPattern = patternStr ? new RegExp(patternStr) : null;

        const isAllowed = allowedOrigins.has(requestOrigin) || (originPattern && originPattern.test(requestOrigin));
        if (!isAllowed) {
          return res.status(403).json({
            success: false,
            statusCode: 403,
            error: 'Cross-origin state-changing request blocked by CSRF defense',
          });
        }
      }
    }
    next();
  });
  app.enableCors({
    origin: buildCorsOriginValidator(),
    methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
    exposedHeaders: ['Content-Disposition'],
    credentials: true,
  });
  app.setGlobalPrefix('api');
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );
  app.useGlobalInterceptors(new ApiResponseInterceptor());
  app.useGlobalFilters(new AllExceptionsFilter());
}
