/* eslint-disable perfectionist/sort-imports -- .env must be loaded before any import that reads process.env */
import 'dotenv/config'
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 FastifyMultipart from '@fastify/multipart'
import Fastify from 'fastify'
import prisma from './prisma/client.ts'

console.log(process.env.DATABASE_URL)

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

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

fastify.register(FastifyCors, {
  origin: [
    'http://localhost:3000',
    'http://tauri.localhost',
    'https://koptilnya.xyz',
    'https://chad.koptilnya.xyz',
  ],
  methods: ['PATCH', 'PUT', 'OPTIONS', 'GET', 'POST', 'DELETE'],
  credentials: true,
})

fastify.register(FastifyCookie)
fastify.register(FastifyMultipart)

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

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

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

  try {
    await fastify.listen({ port, host: '0.0.0.0' })

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