import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import FastifyAutoLoad from '@fastify/autoload'
import FastifyCookie from '@fastify/cookie'
import FastifyCors from '@fastify/cors'
import Fastify from 'fastify'
import prisma from './prisma/client.ts'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const fastify = Fastify({
  logger: true,
})

fastify.register(FastifyCors)

fastify.register(FastifyCookie)

fastify.register(FastifyAutoLoad, {
  dir: join(__dirname, 'plugins'),
})

fastify.register(FastifyAutoLoad, {
  dir: join(__dirname, 'routes'),
})

;(async () => {
  const port = process.env.PORT ? Number(process.env.PORT) : 4000

  try {
    await fastify.listen({ port })

    await prisma.$connect()
    fastify.log.info('Testing DB Connection. OK')
  }
  catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
})()
