import { Request, Response, NextFunction, Router } from 'express';
import { DashboardService } from '../services';

export class DashboardController {
  public router: Router;

  constructor(private readonly dashboardService: DashboardService) {
    this.router = Router();

    this.router.get('/', this.getDashboard.bind(this));
    this.router.get('/kpis', this.getKPIs.bind(this));
    this.router.get('/activity', this.getActivity.bind(this));
    this.router.get('/sales-chart', this.getSalesChart.bind(this));
  }

  private async getDashboard(req: Request, res: Response, next: NextFunction) {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;
      if (!tenantId) {
        res.status(400).json({ error: 'Tenant ID required' });
        return;
      }

      const [kpis, activity, salesChart] = await Promise.all([
        this.dashboardService.getKPIs(tenantId),
        this.dashboardService.getActivity(tenantId),
        this.dashboardService.getSalesChart(tenantId, 'month'),
      ]);

      res.json({
        kpis,
        activity,
        salesChart,
        timestamp: new Date().toISOString(),
      });
    } catch (e) {
      next(e);
    }
  }

  private async getKPIs(req: Request, res: Response, next: NextFunction) {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;
      if (!tenantId) {
        res.status(400).json({ error: 'Tenant ID required' });
        return;
      }

      const kpis = await this.dashboardService.getKPIs(tenantId);
      res.json({ data: kpis });
    } catch (e) {
      next(e);
    }
  }

  private async getActivity(req: Request, res: Response, next: NextFunction) {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;
      if (!tenantId) {
        res.status(400).json({ error: 'Tenant ID required' });
        return;
      }

      const { limit } = req.query;
      const activity = await this.dashboardService.getActivity(
        tenantId,
        limit ? parseInt(limit as string) : 5
      );

      res.json({ data: activity });
    } catch (e) {
      next(e);
    }
  }

  private async getSalesChart(req: Request, res: Response, next: NextFunction) {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;
      if (!tenantId) {
        res.status(400).json({ error: 'Tenant ID required' });
        return;
      }

      const { period } = req.query;
      const validPeriods = ['week', 'month', 'year'];
      const selectedPeriod = validPeriods.includes(period as string)
        ? (period as 'week' | 'month' | 'year')
        : 'month';

      const chartData = await this.dashboardService.getSalesChart(tenantId, selectedPeriod);
      res.json({ data: chartData });
    } catch (e) {
      next(e);
    }
  }
}
