import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { createEnv } from "@t3-oss/env-core";
import { config } from "dotenv";
import { z } from "zod";

// Only load .env file in development (not in Cloudflare Workers)
// Skip if vars are already loaded (e.g., by Vite dev server)
if (process.env.NODE_ENV !== "production" && !process.env.DATABASE_URL) {
	const __dirname = dirname(fileURLToPath(import.meta.url));
	config({ path: resolve(__dirname, "../.env") });
}

export const env = createEnv({
	server: {
		DATABASE_URL: z.string().min(1),
		BETTER_AUTH_SECRET: z.string().min(32),
		BETTER_AUTH_URL: z.url(),
		CORS_ORIGIN: z.url(),
		SMTP_HOST: z.string().min(1).optional(),
		SMTP_PORT: z.coerce.number().default(587),
		SMTP_USER: z.string().min(1).optional(),
		SMTP_PASS: z.string().min(1).optional(),
		SMTP_FROM: z.string().min(1).optional(),
		NODE_ENV: z
			.enum(["development", "production", "test"])
			.default("development"),
		LEMON_SQUEEZY_API_KEY: z.string().min(1).optional(),
		LEMON_SQUEEZY_STORE_ID: z.string().min(1).optional(),
		LEMON_SQUEEZY_VARIANT_ID: z.string().min(1).optional(),
		LEMON_SQUEEZY_WEBHOOK_SECRET: z.string().min(1).optional(),
	},
	runtimeEnv: process.env,
	emptyStringAsUndefined: true,
});
