import { afterEach, describe, expect, it } from "vitest";
import { createConfig } from "../../config.js";
import type { Secrets } from "../../secrets.js";

const baseSecrets: Secrets = {
  adminTokenSigningSecret: "admin-token-signing-secret",
  clientAuthJwtSecret: "client-auth-jwt-secret",
  supabaseServiceRoleKey: "service-role-from-secret-manager",
  supabaseConnectionString: "postgres://secret-manager",
  supabaseCaCert: "ca-cert",
  emailClientSecret: "email-client-secret",
  emailRefreshToken: "email-refresh-token",
  r2AccessKeyId: "r2-access-key-id",
  r2SecretAccessKey: "r2-secret-access-key",
  stripeSecretKey: "sk_live_secret_manager",
  stripeWebhookSecret: "whsec_live_secret_manager",
  stripeSecretKeyStaging: "sk_live_staging_secret_manager",
  stripeWebhookSecretStaging: "whsec_live_staging_secret_manager",
};

const originalEnv = { ...process.env };

afterEach(() => {
  process.env = { ...originalEnv };
});

describe("createConfig stripe env overrides", () => {
  it("prefers env stripe keys in development to avoid local sandbox/account mismatch", () => {
    process.env.NODE_ENV = "development";
    process.env.STRIPE_SECRET_KEY = "sk_test_env_override";
    process.env.STRIPE_WEBHOOK_SECRET = "whsec_test_env_override";

    const config = createConfig(baseSecrets);

    expect(config.STRIPE_SECRET_KEY).toBe("sk_test_env_override");
    expect(config.STRIPE_WEBHOOK_SECRET).toBe("whsec_test_env_override");
  });

  it("derives a staging API base URL instead of localhost when API_BASE_URL is unset", () => {
    process.env.NODE_ENV = "staging";
    process.env.SUPABASE_URL = "https://example.supabase.co";
    process.env.EMAIL_USER = "test@xtablo.com";
    process.env.EMAIL_CLIENT_ID = "client-id";
    process.env.STRIPE_SOLO_PRICE_ID = "price_solo";
    process.env.STRIPE_TEAM_PRICE_ID = "price_team";
    process.env.STRIPE_FOUNDER_PRICE_ID = "price_founder";
    process.env.R2_ACCOUNT_ID = "r2-account";
    process.env.XTABLO_URL = "https://app-staging.xtablo.com";
    delete process.env.API_BASE_URL;

    const config = createConfig(baseSecrets);

    expect(config.API_BASE_URL).toBe("https://api-staging.xtablo.com/api/v1");
  });

  it("loads the client auth JWT secret from Secret Manager in non-test environments", () => {
    process.env.NODE_ENV = "staging";
    process.env.SUPABASE_URL = "https://example.supabase.co";
    process.env.EMAIL_USER = "test@xtablo.com";
    process.env.EMAIL_CLIENT_ID = "client-id";
    process.env.STRIPE_SOLO_PRICE_ID = "price_solo";
    process.env.STRIPE_TEAM_PRICE_ID = "price_team";
    process.env.STRIPE_FOUNDER_PRICE_ID = "price_founder";
    process.env.R2_ACCOUNT_ID = "r2-account";
    delete process.env.CLIENT_AUTH_JWT_SECRET;

    const config = createConfig(baseSecrets);

    expect(config.CLIENT_AUTH_JWT_SECRET).toBe("client-auth-jwt-secret");
  });
});
