import Fastify from 'fastify'
import cors from '@fastify/cors'
import { env } from './config.js'
import { pool } from './db/client.js'
import { ensureDatabaseSchema } from './db/init.js'
import { ensureAdminAccount } from './lib/adminAccount.js'
import { registerAuthRoutes } from './routes/auth.js'
import { registerAdminRoutes } from './routes/admin.js'
import { registerGoalRoutes } from './routes/goals.js'
import { registerPlannerRoutes } from './routes/planner.js'

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

await ensureDatabaseSchema()
await ensureAdminAccount()

await app.register(cors, {
  origin: env.CORS_ORIGIN,
  credentials: true,
})

await registerAuthRoutes(app)
await registerAdminRoutes(app)
await registerGoalRoutes(app)
await registerPlannerRoutes(app)

app.get('/health', async () => {
  const versionResult = await pool.query('select version() as version')
  const version = versionResult.rows[0]

  return {
    status: 'ok',
    service: 'ten-minute-planner-backend',
    database: {
      client: 'postgresql',
      version: version?.version ?? 'unknown',
    },
  }
})

app.get('/api/meta', async () => ({
  auth: 'active',
  storage: 'postgresql',
  orm: 'drizzle',
  notes: [
    '회원가입, 로그인, 현재 사용자 확인 API가 준비되어 있습니다.',
    '관리자용 사용자 현황 요약 API가 준비되어 있습니다.',
    '사용자별 목표 목록, 수정, 삭제 API가 준비되어 있습니다.',
    '사용자별 플래너 저장 및 조회 API가 준비되어 있습니다.',
  ],
}))

try {
  await app.listen({
    port: env.PORT,
    host: '0.0.0.0',
  })
} catch (error) {
  app.log.error(error)
  process.exit(1)
}
