import * as express from "express";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";

// Internal Authentication (สำหรับ Internal Service เช่น .NET)
// ตรวจสอบ API Key จาก Environment Variable (API_KEY)
export async function handleInternalAuth(request: express.Request) {
  // รองรับ header หลายรูปแบบ
  const apiKey =
    request.headers["api-key"] || request.headers["api_key"] || request.headers["apikey"];

  if (!apiKey || typeof apiKey !== "string") {
    throw new HttpError(HttpStatus.UNAUTHORIZED, "API Key is required");
  }

  // ตรวจสอบ API Key จาก Environment Variable (API_KEY)
  if (apiKey !== process.env.API_KEY) {
    console.log(`[InternalAuth] Invalid API key attempt: ${apiKey.substring(0, 5)}...`);
    throw new HttpError(HttpStatus.UNAUTHORIZED, "Invalid API Key");
  }

  // console.log(`[InternalAuth] Authentication successful`);

  return {
    sub: "internal_service",
    preferred_username: "internal_service",
    name: "Internal Service",
    internalKey: true,
  };
}
