import { Router, Response, NextFunction } from 'express'
import prisma from '../lib/prisma'
import { authMiddleware, AuthRequest } from '../middleware/auth'
import { z } from 'zod'

const router = Router()

const createEventSchema = z.object({
  title: z.string().min(1).max(100),
  date: z.string(), // ISO date string
  endDate: z.string().optional(),
  type: z.enum(['CUSTOM', 'MEETING', 'TEAM_BUILDING', 'TRAINING', 'INTERVIEW']).default('CUSTOM'),
  priority: z.enum(['high', 'medium', 'low']).default('medium'),
  location: z.string().optional(),
  description: z.string().optional(),
  employeeId: z.string().optional(),
})

// 获取当月日历事件（自定义 + 系统自动）
router.get('/', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const orgId = req.user!.orgId
    const month = (req.query.month as string) || new Date().toISOString().slice(0, 7)
    const typeFilter = req.query.type as string | undefined

    const [year, mon] = month.split('-').map(Number)
    const monthStart = new Date(year, mon - 1, 1)
    const monthEnd = new Date(year, mon, 0, 23, 59, 59)

    const where: any = {
      orgId,
      date: { gte: monthStart, lte: monthEnd },
    }
    if (typeFilter) where.type = typeFilter

    const events = await prisma.calendarEvent.findMany({
      where,
      include: { employee: { select: { id: true, name: true } } },
      orderBy: { date: 'asc' },
    })

    res.json({ success: true, data: events })
  } catch (err) {
    next(err)
  }
})

// 获取事件详情
router.get('/:id', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const event = await prisma.calendarEvent.findFirst({
      where: { id: req.params.id, orgId: req.user!.orgId },
      include: { employee: { select: { id: true, name: true } } },
    })
    if (!event) return res.status(404).json({ success: false, message: '事件不存在' })
    res.json({ success: true, data: event })
  } catch (err) {
    next(err)
  }
})

// 创建日历事件
router.post('/', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const data = createEventSchema.parse(req.body)
    const event = await prisma.calendarEvent.create({
      data: {
        orgId: req.user!.orgId,
        title: data.title,
        date: new Date(data.date),
        endDate: data.endDate ? new Date(data.endDate) : null,
        type: data.type,
        priority: data.priority,
        location: data.location || null,
        description: data.description || null,
        employeeId: data.employeeId || null,
        createdBy: req.user!.id,
      },
    })
    res.json({ success: true, data: event })
  } catch (err) {
    next(err)
  }
})

// 更新日历事件
router.patch('/:id', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const updateSchema = createEventSchema.partial()
    const data = updateSchema.parse(req.body)
    const updateData: any = { ...data }
    if (data.date) updateData.date = new Date(data.date)
    if (data.endDate) updateData.endDate = new Date(data.endDate)
    if (data.endDate === undefined) delete updateData.endDate

    const event = await prisma.calendarEvent.updateMany({
      where: { id: req.params.id, orgId: req.user!.orgId },
      data: updateData,
    })
    if (event.count === 0) return res.status(404).json({ success: false, message: '事件不存在' })
    res.json({ success: true })
  } catch (err) {
    next(err)
  }
})

// 删除日历事件
router.delete('/:id', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const result = await prisma.calendarEvent.deleteMany({
      where: { id: req.params.id, orgId: req.user!.orgId },
    })
    if (result.count === 0) return res.status(404).json({ success: false, message: '事件不存在' })
    res.json({ success: true })
  } catch (err) {
    next(err)
  }
})

export default router
