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, created } from '../../http/respond'
import * as service from './complaint.service'
import { createSchema, updateSchema, listQuerySchema, idParamSchema } from './complaint.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.listComplaints(req.companyId, query)
    ok(res, result)
  } catch (err) { next(err) }
})

router.post('/', async (req, res, next) => {
  try {
    const body = parseBody(createSchema, req)
    const complaint = await service.createComplaint(req.companyId, body)
    created(res, complaint)
  } catch (err) { next(err) }
})

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

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

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

export default router
