import fp from 'fastify-plugin'
import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import * as storeSchema from '../db/schema/stores.js'
import * as userSchema from '../db/schema/users.js'
import * as accountSchema from '../db/schema/accounts.js'
import * as inventorySchema from '../db/schema/inventory.js'
import * as posSchema from '../db/schema/pos.js'
import * as settingsSchema from '../db/schema/settings.js'

const schema = { ...storeSchema, ...userSchema, ...accountSchema, ...inventorySchema, ...posSchema, ...settingsSchema }

declare module 'fastify' {
  interface FastifyInstance {
    db: ReturnType<typeof drizzle<typeof schema>>
    sql: ReturnType<typeof postgres>
  }
}

export const databasePlugin = fp(async (app) => {
  const connectionString = process.env.DATABASE_URL
  if (!connectionString) {
    throw new Error('DATABASE_URL environment variable is required')
  }

  const sql = postgres(connectionString)
  const db = drizzle(sql, { schema })

  app.decorate('db', db)
  app.decorate('sql', sql)

  app.addHook('onClose', async () => {
    await sql.end()
  })
})
