import { Response } from 'express';
import { prisma } from '../config/database';
import { AuthRequest, ApproverAuthRequest } from '../middleware/auth';

// Apple App Store guideline 5.1.1(v) requires accounts to be deletable from
// inside the app. This endpoint handles three principals:
//   - APPROVER: deletes the legacy Approver row + null-outs assignments
//   - ADMIN:    deletes the Admin row + null-outs assignments / authorships
//   - OWNER:    refuses with a hint (deleting a whole workspace is a
//               heavier flow — needs an explicit confirm + likely email).
// Always removes any DeviceTokens for the principal so the deleted user
// stops getting pushes. Allowed-email entry is deactivated, not deleted,
// so the same address can't immediately re-create the row.
export async function deleteOwnAccount(req: AuthRequest | ApproverAuthRequest, res: Response): Promise<void> {
  try {
    if ('approverId' in req && req.approverId) {
      // Approver path
      const approver = await prisma.approver.findUnique({ where: { id: req.approverId } });
      if (!approver) { res.status(404).json({ error: 'Approver not found' }); return; }

      await prisma.$transaction(async (tx) => {
        // Detach assignments referencing this approver — keep the visitor
        // records but drop the FK so we can delete cleanly.
        await tx.visitor.updateMany({ where: { assignedApproverId: approver.id }, data: { assignedApproverId: null } });
        await tx.visitor.updateMany({ where: { createdByApproverId: approver.id }, data: { createdByApproverId: null } });
        await tx.visitorRequest.updateMany({ where: { assignedApproverId: approver.id }, data: { assignedApproverId: null } });
        await tx.deviceToken.deleteMany({ where: { approverId: approver.id } });
        await tx.allowedEmail.updateMany({ where: { email: approver.email }, data: { isActive: false } });
        await tx.approver.delete({ where: { id: approver.id } });
      });
      res.json({ ok: true, deleted: 'approver' });
      return;
    }

    const authReq = req as AuthRequest;
    if (authReq.adminId) {
      const admin = await prisma.admin.findUnique({ where: { id: authReq.adminId } });
      if (!admin) { res.status(404).json({ error: 'Admin not found' }); return; }

      await prisma.$transaction(async (tx) => {
        await tx.visitor.updateMany({ where: { assignedAdminId: admin.id }, data: { assignedAdminId: null } });
        await tx.visitor.updateMany({ where: { createdByAdminId: admin.id }, data: { createdByAdminId: null } });
        await tx.walkInQR.updateMany({ where: { assignedAdminId: admin.id }, data: { assignedAdminId: null } });
        await tx.walkInQR.updateMany({ where: { createdByAdminId: admin.id }, data: { createdByAdminId: null } });
        await tx.admin.updateMany({ where: { createdByAdminId: admin.id }, data: { createdByAdminId: null } });
        await tx.deviceToken.deleteMany({ where: { adminId: admin.id } });
        await tx.allowedEmail.updateMany({ where: { email: admin.email }, data: { isActive: false } });
        await tx.admin.delete({ where: { id: admin.id } });
      });
      res.json({ ok: true, deleted: 'admin' });
      return;
    }

    // Workspace owner — full delete is destructive (every visitor, admin,
    // walk-in QR, etc. in their workspace would have to go too). Surface a
    // friendly message instead of pretending it's a one-tap action.
    res.status(409).json({
      error:
        "Deleting a workspace owner removes every visitor, admin, walk-in QR, and approver in the workspace. " +
        "Please email support so we can confirm this with you before proceeding.",
    });
  } catch (e) {
    console.error('deleteOwnAccount', e);
    res.status(500).json({ error: 'Failed to delete account' });
  }
}
