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, parseParams, parseQuery } from '../../http/validate'
import { ok } from '../../http/respond'
import * as service from './billing.service'
import {
  billingListQuerySchema,
  billingSummaryQuerySchema,
  invoiceParamSchema,
  manualBillingPaymentSchema,
} from './billing.schemas'

const router = Router()

router.use(requireCompanyAuth, requireTenant, requireSubscription, requireRole('OWNER'))

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

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

router.get('/invoices/:invoiceId', async (req, res, next) => {
  try {
    const { invoiceId } = parseParams(invoiceParamSchema, req)
    ok(res, await service.getInvoice(req.companyId, invoiceId))
  } catch (err) { next(err) }
})

router.post('/invoices/:invoiceId/payments/manual', async (req, res, next) => {
  try {
    const { invoiceId } = parseParams(invoiceParamSchema, req)
    const body = parseBody(manualBillingPaymentSchema, req)
    ok(res, await service.recordManualPayment(req.companyId, req.employee.id, invoiceId, body))
  } catch (err) { next(err) }
})

export default router
