/**
 * Environment Configuration
 * 
 * Validates and exports environment variables with type safety.
 * Throws errors at startup if required variables are missing or invalid.
 */
import { z } from 'zod';

const envSchema = z.object({
  VITE_API_BASE_URL: z.string().url('VITE_API_BASE_URL must be a valid URL'),
  VITE_APP_NAME: z.string().min(1, 'VITE_APP_NAME is required'),
  VITE_REAL_TIME_UPDATE_INTERVAL: z.coerce
    .number()
    .positive('VITE_REAL_TIME_UPDATE_INTERVAL must be a positive number')
    .default(5000),
});

type Env = z.infer<typeof envSchema>;

let env: Env;

try {
  env = envSchema.parse({
    VITE_API_BASE_URL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000',
    VITE_APP_NAME: import.meta.env.VITE_APP_NAME || 'DBIS Admin Console',
    VITE_REAL_TIME_UPDATE_INTERVAL: import.meta.env.VITE_REAL_TIME_UPDATE_INTERVAL || '5000',
  });
} catch (error) {
  if (error instanceof z.ZodError) {
    const errorMessages = error.errors.map((err) => `${err.path.join('.')}: ${err.message}`).join('\n');
    throw new Error(`Invalid environment configuration:\n${errorMessages}`);
  }
  throw error;
}

export { env };
export type { Env };
