import 'dotenv/config'
import express from 'express'
import cors from 'cors'
import { authMiddleware, AuthRequest } from './middleware/auth.js'
import { errorHandler, notFoundHandler } from './middleware/error.js'
import { tenantDbMiddleware } from './middleware/tenant-db.js'
import authRoutes from './routes/auth.js'
import dataRoutes from './routes/data.js'
import taskRoutes from './routes/tasks.js'
import costAnalysisRoutes from './routes/cost-analysis.js'
import storeExpenseRoutes from './routes/store-expense.js'
import smartSchedulingRoutes from './routes/smart-scheduling.js'
import situationalAwarenessRoutes from './routes/situational-awareness.js'
import analyticsEnhancedRoutes from './routes/analytics-enhanced.js'
import adminRoutes from './routes/admin.js'
import ttsRoutes from './routes/tts.js'

const app = express()
const PORT = parseInt(process.env.PORT || '3333')

app.use(cors({
  origin: process.env.CLIENT_URL || true,
  credentials: true,
}))
app.use(express.json())

app.get('/api/health', (req, res) => {
  res.json({ success: true, data: { status: 'ok', time: new Date().toISOString() } })
})

app.use('/api/auth', authRoutes)

// admin login 不需要 auth 中间件
app.post('/api/admin/login', (req, res, next) => {
  req.url = '/login'
  adminRoutes(req, res, next)
})

app.use((req, res, next) => {
  if (req.path === '/api/health' || req.path.startsWith('/api/auth')) {
    return next()
  }
  authMiddleware(req as AuthRequest, res, next)
})

app.use('/api/admin', adminRoutes)

// 租户数据隔离中间件：根据 JWT 中的 tenantId 动态切换数据库连接池
app.use((req, res, next) => {
  if (req.path.startsWith('/api/admin') || req.path === '/api/health' || req.path.startsWith('/api/auth')) {
    return next()
  }
  tenantDbMiddleware(req as AuthRequest, res, next)
})

app.use('/api', dataRoutes)
app.use('/api/tasks', taskRoutes)
app.use('/api/cost-analysis', costAnalysisRoutes)
app.use('/api/store-expense', storeExpenseRoutes)
app.use('/api/smart-scheduling', smartSchedulingRoutes)
app.use('/api/situational-awareness', situationalAwarenessRoutes)
app.use('/api/analytics-enhanced', analyticsEnhancedRoutes)
app.use('/api/tts', ttsRoutes)

app.use(notFoundHandler)
app.use(errorHandler)

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

export default app
