import { plainToInstance } from 'class-transformer';
import { IsString, IsNumber, IsOptional, validateSync } from 'class-validator';

export class EnvironmentVariables {
  @IsString()
  DATABASE_URL!: string;

  @IsString()
  DATABASE_URL_DIRECT!: string;

  @IsString()
  @IsOptional()
  REDIS_HOST?: string;

  @IsNumber()
  @IsOptional()
  REDIS_PORT?: number;

  @IsString()
  @IsOptional()
  REDIS_PASSWORD?: string;

  @IsString()
  @IsOptional()
  JWT_PUBLIC_KEY_PATH?: string;

  @IsString()
  @IsOptional()
  JWT_ISSUER?: string;

  @IsNumber()
  @IsOptional()
  APP_PORT?: number;

  @IsString()
  @IsOptional()
  NODE_ENV?: string;

  @IsString()
  @IsOptional()
  CORS_ORIGINS?: string;

  // Lexware Office Integration (optional)
  @IsString()
  @IsOptional()
  LEXWARE_API_KEY?: string;

  @IsString()
  @IsOptional()
  LEXWARE_API_URL?: string;

  // North Data Integration (optional)
  @IsString()
  @IsOptional()
  NORTH_DATA_API_KEY?: string;

  @IsString()
  @IsOptional()
  NORTH_DATA_API_URL?: string;

  // Core-Service URL fuer interne Kommunikation (Microsoft 365 Token)
  @IsString()
  @IsOptional()
  CORE_SERVICE_URL?: string;
}

export function validate(
  config: Record<string, unknown>,
): EnvironmentVariables {
  const validatedConfig = plainToInstance(EnvironmentVariables, config, {
    enableImplicitConversion: true,
  });

  const errors = validateSync(validatedConfig, {
    skipMissingProperties: false,
  });

  if (errors.length > 0) {
    throw new Error(
      `Umgebungsvariablen-Validierung fehlgeschlagen:\n${errors.toString()}`,
    );
  }

  return validatedConfig;
}
