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

const router = Router()

router.use(requireCompanyAuth, requireTenant, requireSubscription)

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

router.post('/', requireRole('MANAGER'), async (req, res, next) => {
  try {
    const { vehicleIds, ...body } = parseBody(offerSchema, req)
    created(res, await service.createOffer(req.companyId, body, vehicleIds))
  } catch (err) { next(err) }
})

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

router.patch('/:id', requireRole('MANAGER'), async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    const { vehicleIds, ...body } = parseBody(offerSchema.partial(), req)
    ok(res, await service.updateOffer(id, req.companyId, body, vehicleIds))
  } catch (err) { next(err) }
})

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

router.post('/:id/activate', requireRole('MANAGER'), async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    await service.setOfferActive(id, req.companyId, true)
    ok(res, { success: true })
  } catch (err) { next(err) }
})

router.post('/:id/deactivate', requireRole('MANAGER'), async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    await service.setOfferActive(id, req.companyId, false)
    ok(res, { success: true })
  } catch (err) { next(err) }
})

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

export default router
