import { Request, Response } from 'express';
import PDFDocument from 'pdfkit';
import { prisma } from '../models';
import { LicenseStatus } from '@prisma/client';
import { computeDaysRemaining } from '../lib/days-remaining';

export const dashboardController = {
  async licenseStats(req: Request, res: Response) {
    const today = new Date();
    const in30 = new Date(today);
    in30.setDate(today.getDate() + 30);
    const in7 = new Date(today);
    in7.setDate(today.getDate() + 7);

    const [total, active, expired, pendingRenewal, suspended] = await Promise.all([
      prisma.license.count({ where: { deleted_at: null } }),
      prisma.license.count({ where: { deleted_at: null, status: LicenseStatus.ACTIVE } }),
      prisma.license.count({ where: { deleted_at: null, status: LicenseStatus.EXPIRED } }),
      prisma.license.count({ where: { deleted_at: null, status: LicenseStatus.PENDING_RENEWAL } }),
      prisma.license.count({ where: { deleted_at: null, status: LicenseStatus.SUSPENDED } }),
    ]);

    const expiringSoon = await prisma.license.count({
      where: {
        deleted_at: null,
        expiry_date: { lte: in30, gte: today },
        status: { in: [LicenseStatus.ACTIVE, LicenseStatus.PENDING_RENEWAL] },
      },
    });

    const expiring7 = await prisma.license.count({
      where: {
        deleted_at: null,
        expiry_date: { lte: in7, gte: today },
      },
    });

    const byType = await prisma.license.groupBy({
      by: ['license_type'],
      where: { deleted_at: null },
      _count: true,
    });

    res.json({
      success: true,
      data: {
        total,
        active,
        expired,
        pending_renewal: pendingRenewal,
        suspended,
        expiring_within_30_days: expiringSoon,
        expiring_within_7_days: expiring7,
        by_type: byType,
      },
    });
  },

  async licenseSummaryPdf(req: Request, res: Response) {
    const licenses = await prisma.license.findMany({
      where: { deleted_at: null },
      take: 500,
      orderBy: { license_number: 'asc' },
    });

    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename="license-summary.pdf"');

    const doc = new PDFDocument({ margin: 40 });
    doc.pipe(res);
    doc.fontSize(16).text('WM-IMS License Summary Report', { underline: true });
    doc.moveDown();
    doc.fontSize(10);
    for (const l of licenses) {
      const dr = computeDaysRemaining(l.expiry_date);
      doc.text(
        `${l.license_number} | ${l.license_name} | ${l.license_type} | ${l.status} | expires ${l.expiry_date.toISOString().slice(0, 10)} | days: ${dr}`
      );
      doc.moveDown(0.25);
    }
    doc.end();
  },

  async expiringLicenses(req: Request, res: Response) {
    const today = new Date();
    const end = new Date(today);
    end.setDate(today.getDate() + 30);

    const licenses = await prisma.license.findMany({
      where: {
        deleted_at: null,
        expiry_date: { lte: end, gte: today },
      },
      orderBy: { expiry_date: 'asc' },
    });

    const data = licenses.map((l) => ({
      id: l.id,
      license_number: l.license_number,
      license_name: l.license_name,
      expiry_date: l.expiry_date.toISOString().slice(0, 10),
      days_remaining: computeDaysRemaining(l.expiry_date),
      status: l.status,
    }));

    res.json({ success: true, data: { licenses: data } });
  },
};
