import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import * as schema from "./schema";

const connectionString = process.env.DATABASE_URL!;

const queryClient = postgres(connectionString, {
  max: 10,
  idle_timeout: 20,
  max_lifetime: 60 * 30,
  // Force the PostgreSQL session timezone to UTC so that `timestamp without
  // time zone` columns are always stored and returned as UTC values,
  // regardless of what timezone the host OS / Dokploy server is configured
  // with (the Finnish server is UTC+3 in summer).
  connection: { TimeZone: "UTC" },
  // postgres.js v3 parses `timestamp` (OID 1114) with `new Date(rawString)`
  // where rawString looks like "2024-05-28 09:00:00" (space, no Z).  V8
  // treats that space-format string as *local* time, so on any server that
  // isn't UTC the resulting Date object is wrong.  The fix: convert the
  // space-format string to ISO 8601 with an explicit Z so V8 always
  // interprets it as UTC, regardless of the Node.js process timezone.
  types: {
    timestamp: {
      to: 1114,
      from: [1114],
      serialize: (x: Date | string) =>
        (x instanceof Date ? x : new Date(x)).toISOString(),
      parse: (x: string) => new Date(x.replace(" ", "T") + "Z"),
    },
  },
});

// Raw client for queries that need session context
export const sql = queryClient;
export const dbUnscoped = drizzle(queryClient, { schema });

export type Database = typeof dbUnscoped;