// CORS for the public logyou.de landing-page lead intake
// (server/api/webhooks/landing-leads.{post,options}.ts). The landing browser
// form POSTs directly to app.logship.de (no PHP middleman), so the allowlisted
// site origins get CORS headers and double as the browser-path auth check
// (backed by honeypot + per-IP rate limit in the POST handler).
//
// Note: '00.app-auth.ts' middleware only touches the Capacitor app origins
// (https://localhost etc., no port) — 'http://localhost:3005' does not clash.

export const LANDING_LEAD_ORIGINS = new Set([
  'https://logyou.de',
  'https://www.logyou.de',
  'http://localhost:3005', // logyou-landing dev server
])

// deploy.younex.de (dotnews-paas) hands every project a system domain shaped
// like <app>-<8 hex>.younex.de — always available even before a custom domain
// is attached, so pre-launch/staging deploys of the landing live there.
const LANDING_LEAD_ORIGIN_PATTERNS = [/^https:\/\/[a-z0-9-]+\.younex\.de$/]

// Sets the CORS response headers when the request Origin is allowlisted.
// Returns whether the origin was allowed.
export function applyLandingLeadCors(event: any): boolean {
  const origin = getHeader(event, 'origin') || ''
  const allowed = LANDING_LEAD_ORIGINS.has(origin) || LANDING_LEAD_ORIGIN_PATTERNS.some(re => re.test(origin))
  if (allowed) {
    setHeader(event, 'Access-Control-Allow-Origin', origin)
    setHeader(event, 'Vary', 'Origin')
    setHeader(event, 'Access-Control-Allow-Methods', 'POST, OPTIONS')
    setHeader(event, 'Access-Control-Allow-Headers', 'Content-Type')
    setHeader(event, 'Access-Control-Max-Age', '600')
  }
  return allowed
}
