import { Router } from 'express'
import { requireCompanyAuth } from '../../middleware/requireCompanyAuth'
import { requireTenant } from '../../middleware/requireTenant'
import { requireSubscription } from '../../middleware/requireSubscription'
import { parseBody, parseQuery, parseParams } from '../../http/validate'
import { ok } from '../../http/respond'
import * as service from './review.service'
import { replySchema, listQuerySchema, idParamSchema } from './review.schemas'

const router = Router()

router.use(requireCompanyAuth, requireTenant, requireSubscription)

router.get('/', async (req, res, next) => {
  try {
    const query = parseQuery(listQuerySchema, req)
    const result = await service.listReviews(req.companyId, query)
    ok(res, result)
  } catch (err) { next(err) }
})

router.get('/stats', async (req, res, next) => {
  try {
    const stats = await service.getStats(req.companyId)
    ok(res, stats)
  } catch (err) { next(err) }
})

router.get('/:id', async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    const review = await service.getReview(id, req.companyId)
    ok(res, review)
  } catch (err) { next(err) }
})

router.patch('/:id/reply', async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    const { companyReply } = parseBody(replySchema, req)
    const updated = await service.replyToReview(id, req.companyId, companyReply)
    ok(res, updated)
  } catch (err) { next(err) }
})

router.post('/:id/remind', async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    const result = await service.sendReviewReminder(id, req.companyId)
    ok(res, result)
  } catch (err) { next(err) }
})

export default router
