import { defineConfig } from "vite";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.resolve(__dirname, "../..");

function getDevHttpsConfig() {
  return {
    key: fs.readFileSync(path.join(rootDir, "certs/localhost+2-key.pem")),
    cert: fs.readFileSync(path.join(rootDir, "certs/localhost+2.pem"))
  };
}

export default defineConfig(({ command }) => ({
  server: command === "serve"
    ? {
      port: 5174,
      strictPort: true,
      https: getDevHttpsConfig(),
      headers: {
        // 关键：添加 COEP 和 COOP
        "Cross-Origin-Embedder-Policy": "credentialless",  // 或 "require-corp"
        "Cross-Origin-Opener-Policy": "same-origin",
        "Cross-Origin-Resource-Policy": "cross-origin",  // 改为 cross-origin
        // 开发环境允许跨域
        "Access-Control-Allow-Origin": "https://localhost:3000",  // 父页面的地址
        "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
        "Access-Control-Allow-Headers": "Content-Type",
        "Access-Control-Allow-Credentials": "true"
      },
      proxy: {
        "/api": "http://127.0.0.1:3001",
        "/storage": "http://127.0.0.1:3001"
      }
    }
    : undefined
}));
