import express, { type Express } from 'express';
import helmet from 'helmet';
import cors from 'cors';
import compression from 'compression';
import cookieParser from 'cookie-parser';
import pinoHttp from 'pino-http';
import { env } from './config/env';
import { logger } from './lib/logger';
import { pingDb } from './db/knex';
import { errorHandler, notFoundHandler } from './middleware/errors';
import { healthRouter } from './modules/public/health.routes';
import { publicRouter } from './modules/public';
import { adminRouter } from './modules/admin';
import { websiteRouter } from './ssr/website';
import { analyticsOrigin } from './seo/monitoring';

export type AppDeps = { ping?: () => Promise<boolean>; website?: boolean };

/**
 * ONE app for both front ends (BACKEND.md §0):
 *   /api/v1/...        public website (read-only)
 *   /api/v1/admin/...  admin panel (login required)
 *   everything else    the website itself, rendered on the server (SEO Phase 1)
 */
export function createApp(deps: AppDeps = {}): Express {
  const app = express();

  // cPanel/Passenger and Cloudflare sit in front of the app: trust the first proxy hop for req.ip.
  app.set('trust proxy', 1);
  app.disable('x-powered-by');

  // JSON API: no HTML, so the strictest policy. Website pages: own scripts only, images also from R2.
  const apiHelmet = helmet({
    contentSecurityPolicy: { directives: { defaultSrc: ["'none'"], frameAncestors: ["'none'"] } },
    crossOriginResourcePolicy: { policy: 'same-site' },
  });
  const siteHelmet = helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", ...(analyticsOrigin() ? [analyticsOrigin()!] : [])],
        styleSrc: ["'self'", "'unsafe-inline'"], // React `style={…}` attributes
        imgSrc: ["'self'", 'data:', 'blob:', ...(env.R2_PUBLIC_URL ? [env.R2_PUBLIC_URL] : [])],
        fontSrc: ["'self'", 'data:'],
        connectSrc: ["'self'", ...(analyticsOrigin() ? [analyticsOrigin()!] : [])],
        objectSrc: ["'none'"],
        baseUri: ["'self'"],
        frameAncestors: ["'none'"],
        formAction: ["'self'"],
      },
    },
  });
  app.use((req, res, next) => (req.path.startsWith('/api/') ? apiHelmet : siteHelmet)(req, res, next));
  app.use(
    cors({
      origin(origin, cb) {
        // Allow server-to-server calls (no Origin) and the allowlisted website + admin origins only.
        if (!origin || env.CORS_ORIGINS.includes(origin)) return cb(null, true);
        cb(null, false);
      },
      credentials: true, // admin cookie
      methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
      maxAge: 600,
    }),
  );
  app.use(compression());
  app.use(express.json({ limit: '1mb' }));
  app.use(cookieParser());
  app.use(pinoHttp({ logger, autoLogging: { ignore: (req) => req.url === '/api/v1/health' } }));

  // the API is never a search result (SEO Phase 6); the admin site sends the same header from its .htaccess
  app.use('/api', (_req, res, next) => {
    res.set('X-Robots-Tag', 'noindex, nofollow');
    next();
  });
  app.use('/api/v1', healthRouter(deps.ping ?? (() => pingDb())));
  app.use('/api/v1/admin', adminRouter());
  app.use('/api/v1', publicRouter());

  // the website (server-rendered) for every non-API path, when a website build is present
  const site = deps.website === false ? null : websiteRouter();
  if (site) app.use((req, res, next) => (req.path.startsWith('/api/') ? next() : site(req, res, next)));

  app.use(notFoundHandler);
  app.use(errorHandler);
  return app;
}
