import { drizzle } from 'drizzle-orm/libsql';
import { createClient, type Config } from '@libsql/client';
import * as schema from './schema';

let dbInstance: ReturnType<typeof drizzle<typeof schema>> | null = null;

export function getDb() {
  if (dbInstance) {
    return dbInstance;
  }

  let config: Config;
  
  const remoteUrl = typeof process !== 'undefined' && process.env?.ASTRO_DB_REMOTE_URL
    ? process.env.ASTRO_DB_REMOTE_URL
    : './dev.db';
  
  const authToken = typeof process !== 'undefined' && process.env?.ASTRO_DB_APP_TOKEN
    ? process.env.ASTRO_DB_APP_TOKEN
    : undefined;

  if (remoteUrl.startsWith('file:') || remoteUrl.startsWith('libsql:')) {
    config = {
      url: remoteUrl,
      authToken: authToken
    };
  } else {
    config = {
      url: `file:${remoteUrl}`
    };
  }

  const client = createClient(config);
  dbInstance = drizzle(client, { schema });
  return dbInstance;
}

export const db = getDb();

export type ConsentLog = typeof schema.ConsentLog.$inferSelect;
export type NewConsentLog = typeof schema.ConsentLog.$inferInsert;
