require('dotenv').config()
const express = require('express')
const cors    = require('cors')

const authorsRouter      = require('./routes/authors')
const booksRouter        = require('./routes/books')
const borrowRecordsRouter = require('./routes/borrowRecords')

const app  = express()
const PORT = process.env.PORT || 3001

// ── Middleware ────────────────────────────────────────────────────────────

app.use(cors({
  origin: [
    'http://localhost:3000',  // Vite default
    'http://localhost:5173',  // Vite alt port
  ]
}))

app.use(express.json())

// ── Routes ────────────────────────────────────────────────────────────────

app.use('/api/authors',       authorsRouter)
app.use('/api/books',         booksRouter)
app.use('/api/borrowrecords', borrowRecordsRouter)

// ── Health check ──────────────────────────────────────────────────────────

app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() })
})

// ── 404 handler ───────────────────────────────────────────────────────────

app.use((req, res) => {
  res.status(404).json({ message: `Route ${req.method} ${req.path} not found.` })
})

// ── Global error handler ──────────────────────────────────────────────────

app.use((err, req, res, next) => {
  console.error('Unhandled error:', err)
  res.status(500).json({ message: 'An unexpected server error occurred.' })
})

// ── Start ─────────────────────────────────────────────────────────────────

app.listen(PORT, () => {
  console.log(`🚀 Library API running on http://localhost:${PORT}`)
})