import { config } from "dotenv";
import { defineConfig } from "drizzle-kit";

// Prefer .env.local (Next.js convention), then .env.production, then .env
config({ path: ".env.local" });
config({ path: ".env.production" });
config();

// Allow discrete DB_* vars from host panels
if (!process.env.DATABASE_URL) {
  const host = process.env.DB_HOST;
  const user = process.env.DB_USER;
  const password = process.env.DB_PASSWORD ?? "";
  const name = process.env.DB_NAME;
  const port = process.env.DB_PORT ?? "5432";
  if (host && user && name) {
    const ssl = String(process.env.DB_SSL ?? process.env.SSL ?? "").toLowerCase();
    const useSsl = ssl === "true" || ssl === "1" || ssl === "require";
    const auth = `${encodeURIComponent(user)}:${encodeURIComponent(password)}`;
    process.env.DATABASE_URL = `postgresql://${auth}@${host}:${port}/${name}${
      useSsl ? "?sslmode=require" : ""
    }`;
  }
}

if (!process.env.DATABASE_URL) {
  throw new Error(
    "DATABASE_URL is required for drizzle-kit. Set it in .env.local (or DB_* parts).",
  );
}

export default defineConfig({
  schema: "./src/core/db/schema/index.ts",
  out: "./drizzle",
  dialect: "postgresql",
  dbCredentials: {
    url: process.env.DATABASE_URL,
  },
  strict: false,
  verbose: true,
});
