import { Request, Response, NextFunction } from "express";
import {HttpStatusCode} from "../api/apiHelpers/HttpStatusCodes.js";

/**
 * Add CORS header
 * 
 * CORS (Cross-Origin Resource Sharing) must be enabled for the web app
 * to communicate with the backehd
 */
export function corsHeaders (req: Request, res: Response, next: NextFunction) {
    // allow requests from all sources (*) for now
    // @todo restrict access!
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      
      // Handle preflight requests quickly
      if (req.method === 'OPTIONS') {
        return res.sendStatus(HttpStatusCode.OK);
      }

      next();
    }