import { Router } from 'express'

import {
  closeTencentBrowserSession,
  createTencentBrowserSession,
  getTencentBrowserSession,
  getTencentBrowserSessionSummary,
  getTencentBrowserSessionScreenshotPath,
  reloadTencentBrowserSession,
  redeemTencentBrowserSession,
} from '../services/session/session.js'
import {
  buildNotFoundPayload,
  buildSuccessPayload,
  sendRouteError,
} from '../utils/http.js'

const router = Router()

router.post('/browser/session', async (req, res) => {
  try {
    const data = await createTencentBrowserSession(req.body)
    res.json(buildSuccessPayload(data, '浏览器会话已创建'))
  } catch (error) {
    sendRouteError(res, error, '创建浏览器会话失败', '[browser/session]')
  }
})

router.get('/browser/session/:sessionId', async (req, res) => {
  try {
    const data = await getTencentBrowserSession(req.params.sessionId)
    res.json(buildSuccessPayload(data, data.notice || 'ok'))
  } catch (error) {
    sendRouteError(res, error, '查询浏览器会话失败', '[browser/session/:sessionId]')
  }
})

router.get('/browser/session/:sessionId/summary', async (req, res) => {
  try {
    const data = await getTencentBrowserSessionSummary(req.params.sessionId)
    res.json(buildSuccessPayload(data, data.notice || 'ok'))
  } catch (error) {
    sendRouteError(res, error, '查询浏览器会话摘要失败', '[browser/session/:sessionId/summary]')
  }
})

router.post('/browser/session/:sessionId/refresh', async (req, res) => {
  try {
    const data = await reloadTencentBrowserSession(req.params.sessionId)
    res.json(buildSuccessPayload(data, data.notice || '后端页面已刷新'))
  } catch (error) {
    sendRouteError(res, error, '刷新后端页面失败', '[browser/session/:sessionId/refresh]')
  }
})

router.post('/browser/session/:sessionId/redeem', async (req, res) => {
  try {
    const data = await redeemTencentBrowserSession(req.params.sessionId, req.body)
    res.json(buildSuccessPayload(data, data.notice || '兑换完成'))
  } catch (error) {
    sendRouteError(res, error, '浏览器会话兑换失败', '[browser/session/:sessionId/redeem]')
  }
})

router.get('/browser/session/:sessionId/screenshot', async (req, res) => {
  try {
    const screenshotPath = await getTencentBrowserSessionScreenshotPath(req.params.sessionId)
    res.sendFile(screenshotPath)
  } catch (error) {
    sendRouteError(res, error, '读取兑换截图失败', '[browser/session/:sessionId/screenshot]')
  }
})

router.delete('/browser/session/:sessionId', async (req, res) => {
  try {
    const data = await closeTencentBrowserSession(req.params.sessionId)
    res.json(buildSuccessPayload(data, '浏览器会话已关闭'))
  } catch (error) {
    sendRouteError(res, error, '关闭浏览器会话失败', '[browser/session/:sessionId]')
  }
})

router.use((req, res) => {
  res.status(404).json(buildNotFoundPayload(req))
})

export default router
