import { Router } from 'express'
import { db } from '../db.js'

const router = Router()

router.get('/', async (_req, res) => {
  try {
    const result = await db.query(
      'SELECT id, started_at, ended_at, title FROM meetings ORDER BY started_at DESC'
    )
    res.json(result.rows)
  } catch (err) {
    res.status(500).json({ message: '대화 목록을 불러오지 못했습니다.' })
  }
})

router.get('/:id', async (req, res) => {
  const meetingId = Number(req.params.id)
  if (!meetingId) {
    return res.status(400).json({ message: '잘못된 meeting id입니다.' })
  }

  try {
    const meetingResult = await db.query(
      'SELECT id, started_at, ended_at, title FROM meetings WHERE id = $1',
      [meetingId]
    )
    if (meetingResult.rowCount === 0) {
      return res.status(404).json({ message: '대화를 찾을 수 없습니다.' })
    }

    const utterancesResult = await db.query(
      'SELECT id, meeting_id, speaker, text, ts FROM utterances WHERE meeting_id = $1 ORDER BY ts ASC',
      [meetingId]
    )
    const answersResult = await db.query(
      'SELECT id, meeting_id, question_text, suggestions, created_at FROM answers WHERE meeting_id = $1 ORDER BY created_at ASC',
      [meetingId]
    )

    return res.json({
      meeting: meetingResult.rows[0],
      utterances: utterancesResult.rows,
      answers: answersResult.rows,
    })
  } catch (err) {
    return res.status(500).json({ message: '대화 정보를 불러오지 못했습니다.' })
  }
})

router.post('/', async (req, res) => {
  const { started_at } = req.body as { started_at?: string }
  if (!started_at) {
    return res.status(400).json({ message: 'started_at이 필요합니다.' })
  }

  try {
    const result = await db.query(
      'INSERT INTO meetings (started_at) VALUES ($1) RETURNING id',
      [started_at]
    )
    return res.json({ id: result.rows[0].id })
  } catch (err) {
    return res.status(500).json({ message: '대화를 시작하지 못했습니다.' })
  }
})

router.post('/:id/end', async (req, res) => {
  const meetingId = Number(req.params.id)
  const { ended_at, title } = req.body as { ended_at?: string; title?: string }
  if (!meetingId || !ended_at) {
    return res.status(400).json({ message: 'meeting id와 ended_at이 필요합니다.' })
  }

  try {
    await db.query('UPDATE meetings SET ended_at = $1, title = $2 WHERE id = $3', [
      ended_at,
      title || null,
      meetingId,
    ])
    return res.json({ ok: true })
  } catch (err) {
    return res.status(500).json({ message: '대화를 종료하지 못했습니다.' })
  }
})

router.post('/:id/utterances', async (req, res) => {
  const meetingId = Number(req.params.id)
  const { text, ts } = req.body as { text?: string; ts?: string }
  if (!meetingId || !text) {
    return res.status(400).json({ message: 'meeting id와 text가 필요합니다.' })
  }

  try {
    await db.query(
      'INSERT INTO utterances (meeting_id, text, ts) VALUES ($1, $2, $3)',
      [meetingId, text, ts || new Date().toISOString()]
    )
    return res.json({ ok: true })
  } catch (err) {
    return res.status(500).json({ message: '발화를 저장하지 못했습니다.' })
  }
})

router.post('/:id/answers', async (req, res) => {
  const meetingId = Number(req.params.id)
  const { question_text, suggestions } = req.body as {
    question_text?: string
    suggestions?: string[]
  }
  if (!meetingId || !question_text || !Array.isArray(suggestions)) {
    return res.status(400).json({ message: '질문과 답변 후보가 필요합니다.' })
  }

  try {
    await db.query(
      'INSERT INTO answers (meeting_id, question_text, suggestions) VALUES ($1, $2, $3)',
      [meetingId, question_text, JSON.stringify(suggestions)]
    )
    return res.json({ ok: true })
  } catch (err) {
    return res.status(500).json({ message: '답변 후보를 저장하지 못했습니다.' })
  }
})

router.delete('/', async (req, res) => {
  const { ids } = req.body as { ids?: number[] }
  if (!Array.isArray(ids) || ids.length === 0) {
    return res.status(400).json({ message: '삭제할 id 목록이 필요합니다.' })
  }

  const client = await db.connect()
  try {
    await client.query('BEGIN')
    await client.query('DELETE FROM meetings WHERE id = ANY($1)', [ids])
    await client.query('COMMIT')
    return res.json({ ok: true })
  } catch (err) {
    await client.query('ROLLBACK')
    return res.status(500).json({ message: '대화를 삭제하지 못했습니다.' })
  } finally {
    client.release()
  }
})

export default router
