import { defineConfig, loadEnv } from "@medusajs/framework/utils"

loadEnv(process.env.NODE_ENV || "development", process.cwd())

const required = (name: string): string => {
  const value = process.env[name]
  if (!value) {
    throw new Error(`La variable ${name} es obligatoria.`)
  }
  return value
}

module.exports = defineConfig({
  projectConfig: {
    databaseUrl: required("DATABASE_URL"),
    redisUrl: required("REDIS_URL"),
    workerMode: (process.env.MEDUSA_WORKER_MODE || "shared") as
      | "shared"
      | "worker"
      | "server",
    http: {
      storeCors: required("STORE_CORS"),
      adminCors: required("ADMIN_CORS"),
      authCors: required("AUTH_CORS"),
      jwtSecret: required("JWT_SECRET"),
      cookieSecret: required("COOKIE_SECRET"),
    },
    // Todos los Ingress del lab terminan en Traefik por HTTP plano
    // (entrypoint "web", sin TLS); Cloudflare es quien atiende HTTPS de
    // cara al navegador. Con `secure: true` (el default en producción),
    // express-session nunca emite Set-Cookie porque no detecta la
    // conexión como HTTPS, y el dashboard admin queda con 401 en
    // /admin/users/me pese a loguear bien. La API con Bearer token no se
    // ve afectada por esto.
    cookieOptions: {
      secure: false,
    },
  },

  admin: {
    disable: process.env.DISABLE_MEDUSA_ADMIN === "true",
    backendUrl:
      process.env.MEDUSA_BACKEND_URL ||
      "https://commerce.cruzcloud.net",
    storefrontUrl:
      process.env.STOREFRONT_URL ||
      "https://shop.cruzcloud.net",
  },

  modules: [
    {
      resolve: "@medusajs/medusa/file",
      options: {
        providers: [
          {
            resolve: "@medusajs/medusa/file-s3",
            id: "s3",
            options: {
              file_url: required("S3_FILE_URL"),
              access_key_id: required("S3_ACCESS_KEY_ID"),
              secret_access_key: required("S3_SECRET_ACCESS_KEY"),
              region: process.env.S3_REGION || "us-east-1",
              bucket: required("S3_BUCKET"),
              endpoint: required("S3_ENDPOINT"),
              cache_control:
                "public, max-age=31536000, immutable",
              additional_client_config: {
                forcePathStyle: true,
              },
            },
          },
        ],
      },
    },
  ],
})
