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 { parseQuery } from '../../http/validate'
import { ok } from '../../http/respond'
import * as service from './analytics.service'
import { summaryQuerySchema, reportQuerySchema } from './analytics.schemas'

const router = Router()

router.use(requireCompanyAuth, requireTenant, requireSubscription)

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

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

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

router.get('/report', requireRole('MANAGER'), async (req, res, next) => {
  try {
    const query  = parseQuery(reportQuerySchema, req)
    const result = await service.getReport(req.companyId, query)
    if (result.format === 'CSV') {
      const start = result.startDate.toISOString().slice(0, 10)
      const end   = result.endDate.toISOString().slice(0, 10)
      res.setHeader('Content-Type', 'text/csv')
      res.setHeader('Content-Disposition', `attachment; filename="report-${start}-${end}.csv"`)
      return res.send(result.csv)
    }
    ok(res, result.report)
  } catch (err) { next(err) }
})

export default router
