import { config as dotenvConfig } from 'dotenv';
import { z } from 'zod';
import path from 'path';
import { fileURLToPath } from 'url';

// Load .env from parent directory (workspace root)
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenvConfig({ path: path.join(__dirname, '../../../.env') });

// Local product identity (replaces @bytelyst/config)
const productIdentity = {
  productId: process.env.PRODUCT_ID || 'bytelyst-devops',
  name: process.env.PRODUCT_NAME || 'ByteLyst DevOps Dashboard',
};

const envSchema = z.object({
  PORT: z.string().default('4004'),
  PLATFORM_SERVICE_URL: z.string().url(),
  COSMOS_ENDPOINT: z.string().url(),
  COSMOS_KEY: z.string().min(1),
  COSMOS_DATABASE: z.string().min(1),
  JWT_SECRET: z.string().min(1),
  CSRF_SECRET: z.string().min(1).default('default-csrf-secret-change-in-production'),
  ENCRYPTION_KEY: z.string().min(1).default('default-encryption-key-change-in-production'),
  AZURE_TENANT_ID: z.string().optional(),
  AZURE_CLIENT_ID: z.string().optional(),
  AZURE_CLIENT_SECRET: z.string().optional(),
  AZURE_KEY_VAULT_URL: z.string().url().optional(),
});

export const config = envSchema.parse(process.env);

// Warn loudly when insecure default keys are in use
if (config.CSRF_SECRET === 'default-csrf-secret-change-in-production') {
  console.warn('[config] WARNING: CSRF_SECRET is using the insecure default — set CSRF_SECRET in .env before deploying to production');
}
if (config.ENCRYPTION_KEY === 'default-encryption-key-change-in-production') {
  console.warn('[config] WARNING: ENCRYPTION_KEY is using the insecure default — set ENCRYPTION_KEY in .env before deploying to production');
}

export const productId = productIdentity.productId;
export const productName = productIdentity.name;
