import { Request, Response } from 'express';
import { prisma } from '../models';
import { LicenseStatus, PitStatus } from '@prisma/client';
import { NotificationService } from '../services/notification.service';
import { writeAudit } from '../lib/audit';

export const killSwitchController = {
  async trigger(req: Request, res: Response) {
    const { licenseId } = req.params;
    const license = await prisma.license.findFirst({ where: { id: licenseId, deleted_at: null } });
    if (!license) {
      res.status(404).json({ success: false, error: 'Not found' });
      return;
    }

    await prisma.$transaction(async (tx) => {
      await tx.license.update({
        where: { id: licenseId },
        data: { status: LicenseStatus.EXPIRED, days_remaining: 0 },
      });
      await tx.pit.updateMany({
        where: { license_id: licenseId, deleted_at: null },
        data: { status: PitStatus.DISABLED, operational_access: false },
      });
      await tx.killSwitchLog.create({
        data: {
          license_id: licenseId,
          license_number: license.license_number,
          trigger_date: new Date(),
          days_remaining: 0,
          action_taken: 'ACCESS_REVOKED',
          notified_md: true,
          notified_legal: true,
        },
      });
    });

    await NotificationService.sendLicenseExpiredAlert(license);
    await writeAudit(req, 'KILL_SWITCH', 'License', licenseId);

    res.json({ success: true, message: 'Kill-switch executed' });
  },

  async logs(req: Request, res: Response) {
    const logs = await prisma.killSwitchLog.findMany({ orderBy: { created_at: 'desc' }, take: 500 });
    res.json({ success: true, data: { logs } });
  },
};
