import path from 'node:path';
import process from 'node:process';
import compression from 'compression';
import config from 'config';
import { RedisStore } from 'connect-redis';
import { parseCookie } from 'cookie';
import express, { Router } from 'express';
import session from 'express-session';

import { verifyKey } from '../auth.js';
import initLogger from '../logger.js';

import redis from '../redis.js';
import queryBoolean from '../utils/query-boolean.js';

import { actorsRouter } from './actors.js';
import { alertsRouter } from './alerts.js';
import { authRouter, setUserApi } from './auth.js';

import consentHandler from './consent.js';

import { fetchEntitiesApi } from './entities.js';
import errorHandler from './error.js';
import { graphqlApi } from './graphql.js';

import mainHandler from './main.js';
import { fetchMoviesApi } from './movies.js';

import initRestrictionHandler from './restrictions.js';

import { scenesRouter } from './scenes.js';
import serializeApiResponses from './serialize.js';

import { router as stashesRouter } from './stashes.js';
import { syncRouter } from './sync.js';
import { initCachesApi } from './system.js';

import { fetchTagsApi } from './tags.js';

import { router as userRouter } from './users.js';

const logger = initLogger();
const isProduction = process.env.NODE_ENV === 'production';

export default async function initServer() {
	const app = express();
	const router = Router();
	const restrictionHandler = await initRestrictionHandler();

	app.use(compression());
	app.disable('x-powered-by');
	app.set('view engine', 'ejs');
	// Express 5 defaults to the 'simple' query parser (Node's querystring) instead of 'extended'
	// (qs), which drops support for the bracket/nested query syntax the app relies on.
	app.set('query parser', 'extended');

	router.use(queryBoolean());

	router.use('/', express.static('public'));
	router.use('/', express.static('static'));
	router.use('/media', express.static(config.media.path));

	router.use((req, _res, next) => {
		if (req.headers.cookie) {
			const cookies = parseCookie(req.headers.cookie);

			req.cookies = cookies;
			req.tagFilter = cookies.tags ? JSON.parse(cookies.tags) : [];
		}

		next();
	});

	router.use(express.json());

	const redisStore = new RedisStore({
		client: redis,
		prefix: 'traxxx:session:',
	});

	router.use(session({
		...config.web.session,
		store: redisStore,
	}));

	// Vite integration
	if (isProduction) {
		app.enable('trust proxy');

		// In production, we need to serve our static assets ourselves.
		// (In dev, Vite's middleware serves our static assets.)
		const sirv = (await import('sirv')).default;
		router.use(sirv('dist/client'));
	}
	else {
		// We instantiate Vite's development server and integrate its middleware to our server.
		// ⚠️ We instantiate it only in development. (It isn't needed in production and it
		// would unnecessarily bloat our production server.)
		const vite = await import('vite');

		const viteDevMiddleware = (
			await vite.createServer({
				// root,
				server: { middlewareMode: true },
			})
		).middlewares;

		router.use(viteDevMiddleware);
	}

	router.use(setUserApi); // we need to set the IP before the restriction handler
	router.use(restrictionHandler);

	router.get('/consent', (_req, res) => {
		res.sendFile(path.join(import.meta.dirname, '../../assets/consent.html'));
	});

	router.use('/api/{*splat}', serializeApiResponses);

	router.use('/api/{*splat}', async (req, _res, next) => {
		if (req.headers['api-user']) {
			req.user = await verifyKey(req.headers['api-user'], req.headers['api-key'], req);
		}

		next();
	});

	router.use(userRouter);
	router.use(stashesRouter);
	router.use(alertsRouter);
	router.use(authRouter);
	router.use(scenesRouter);
	router.use(actorsRouter);
	router.use(syncRouter);

	// MOVIES
	router.get('/api/movies', fetchMoviesApi);

	// ENTITIES
	router.get('/api/entities', fetchEntitiesApi);

	// TAGS
	router.get('/api/tags', fetchTagsApi);

	router.post('/api/caches', initCachesApi);

	if (config.apiAccess.graphqlEnabled) {
		router.post('/graphql', graphqlApi);
	}

	router.use(consentHandler);

	router.use((_req, res, next) => {
		res.set('Accept-CH', 'Sec-CH-Prefers-Color-Scheme');
		res.set('Vary', 'Sec-CH-Prefers-Color-Scheme');
		res.set('Critical-CH', 'Sec-CH-Prefers-Color-Scheme');

		next();
	});

	router.get('/{*splat}', mainHandler);

	router.use(errorHandler);
	app.use(router);

	const port = process.env.PORT || config.web.port || 3000;
	// const port = Math.round(Math.random() * 10000);

	app.listen(port, config.web.host);

	logger.info(`Server running at http://${config.web.host}:${port}`);
}
