import { Router } from "express";
import { z } from "zod";
import type { Prisma } from "@prisma/client";
import { prisma } from "../prisma.js";
import { requireAuth, type AuthedRequest } from "../middleware/auth.js";
import { requirePermission } from "../middleware/permissions.js";
import { writeAuditEvent } from "../services/auditEventService.js";
import { ensureAppendOnlyPermissions } from "../services/permissionCatalog.js";

const router = Router();
router.use(requireAuth);
router.use(requirePermission("admin:permissions"));

async function auditMembershipScope(userId: bigint) {
  return prisma.projectUser.findFirst({
    where: { userId },
    select: { projectId: true },
    orderBy: { id: "desc" },
  });
}

async function ensureAuditPermissionsExist() {
  const auditPermissions = [
    {
      key: "view:audit-trail",
      label: "View audit trail",
      category: "audit",
      description: "Can view project audit events and timeline.",
    },
    {
      key: "export:audit-trail",
      label: "Export audit trail",
      category: "audit",
      description: "Can export audit events as CSV/JSON.",
    },
    {
      key: "verify:audit-integrity",
      label: "Verify audit integrity chain",
      category: "audit",
      description: "Can run audit chain integrity checks.",
    },
  ] as const;
  for (const perm of auditPermissions) {
    await prisma.permission.upsert({
      where: { key: perm.key },
      create: perm,
      update: {
        label: perm.label,
        category: perm.category,
        description: perm.description,
      },
      select: { id: true },
    });
  }
}

async function ensureActivityManagementPermissionExists() {
  const perm = {
    key: "manage:activities",
    label: "Manage activities",
    category: "activity",
    description: "Can create/edit project activities and assignment to providers.",
  } as const;
  await prisma.permission.upsert({
    where: { key: perm.key },
    create: perm,
    update: { label: perm.label, category: perm.category, description: perm.description },
    select: { id: true },
  });
}

async function ensureActivityWindowsManagementPermissionExists() {
  const perm = {
    key: "manage:activity-windows",
    label: "Manage activity windows",
    category: "activity",
    description: "Can configure delivery activity submission deadlines (duration rules).",
  } as const;
  await prisma.permission.upsert({
    where: { key: perm.key },
    create: perm,
    update: { label: perm.label, category: perm.category, description: perm.description },
    select: { id: true },
  });
}

async function ensureAttendanceInsightsPermissionExists() {
  const perm = {
    key: "view:attendance-insights",
    label: "View attendance insights",
    category: "attendance",
    description: "Can view attendance insights dashboard and trend analysis.",
  } as const;
  await prisma.permission.upsert({
    where: { key: perm.key },
    create: perm,
    update: { label: perm.label, category: perm.category, description: perm.description },
    select: { id: true },
  });
}

async function ensureDropoutMonitoringPermissionExists() {
  const perm = {
    key: "view:dropout-monitoring",
    label: "View dropout monitoring",
    category: "attendance",
    description: "Can view attendance-based dropout monitoring and composite dropout statuses.",
  } as const;
  await prisma.permission.upsert({
    where: { key: perm.key },
    create: perm,
    update: { label: perm.label, category: perm.category, description: perm.description },
    select: { id: true },
  });
}

router.get("/permissions", async (_req, res) => {
  await ensureAppendOnlyPermissions(prisma);
  await ensureAuditPermissionsExist();
  await ensureActivityManagementPermissionExists();
  await ensureActivityWindowsManagementPermissionExists();
  await ensureAttendanceInsightsPermissionExists();
  await ensureDropoutMonitoringPermissionExists();
  const permissions = await prisma.permission.findMany({
    orderBy: [{ category: "asc" }, { key: "asc" }],
    select: { id: true, key: true, label: true, category: true, description: true },
  });
  res.json({
    permissions: permissions.map((p: (typeof permissions)[number]) => ({ ...p, id: p.id.toString() })),
  });
});

router.get("/roles", async (_req, res) => {
  const roles = await prisma.role.findMany({
    orderBy: [{ isSystem: "desc" }, { label: "asc" }],
    include: {
      rolePermissions: {
        where: { allowed: true },
        include: { permission: { select: { key: true } } },
      },
    },
  });
  res.json({
    roles: roles.map((r: (typeof roles)[number]) => ({
      id: r.id.toString(),
      code: r.code,
      label: r.label,
      description: r.description,
      isSystem: r.isSystem,
      permissions: r.rolePermissions.map((rp: (typeof r.rolePermissions)[number]) => rp.permission.key),
    })),
  });
});

router.post("/roles", async (req: AuthedRequest, res) => {
  const parsed = z
    .object({
      code: z.string().min(2).max(100).regex(/^[a-z][a-z0-9_]*$/),
      label: z.string().min(2).max(191),
      description: z.string().max(2000).optional(),
    })
    .safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    return;
  }
  try {
    const created = await prisma.role.create({
      data: {
        code: parsed.data.code.trim(),
        label: parsed.data.label.trim(),
        description: parsed.data.description?.trim() || null,
        isSystem: false,
      },
      select: { id: true, code: true, label: true, description: true, isSystem: true },
    });
    const m = await auditMembershipScope(req.auth!.userId);
    if (m) {
      await writeAuditEvent({
        projectId: m.projectId,
        module: "rbac",
        action: "role_created",
        sourceType: "role",
        sourceRef: created.id.toString(),
        payloadRaw: JSON.stringify({ code: created.code, label: created.label }),
        actorUserId: req.auth!.userId,
      });
    }
    res.json({
      role: { ...created, id: created.id.toString(), permissions: [] as string[] },
    });
  } catch {
    res.status(422).json({ error: "Could not create role (code may already exist)." });
  }
});

router.put("/roles/:roleId/permissions", async (req: AuthedRequest, res) => {
  const roleId = BigInt(req.params.roleId);
  const parsed = z.object({ permissionKeys: z.array(z.string()).default([]) }).safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    return;
  }

  const role = await prisma.role.findUnique({ where: { id: roleId }, select: { id: true } });
  if (!role) {
    res.status(404).json({ error: "Role not found." });
    return;
  }

  const perms = await prisma.permission.findMany({
    where: { key: { in: parsed.data.permissionKeys } },
    select: { id: true },
  });

  await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
    await tx.rolePermission.deleteMany({ where: { roleId } });
    if (perms.length) {
      await tx.rolePermission.createMany({
        data: perms.map((p: (typeof perms)[number]) => ({ roleId, permissionId: p.id, allowed: true })),
      });
    }
  });
  const m = await auditMembershipScope(req.auth!.userId);
  if (m) {
    await writeAuditEvent({
      projectId: m.projectId,
      module: "rbac",
      action: "role_permissions_updated",
      sourceType: "role",
      sourceRef: roleId.toString(),
      payloadRaw: JSON.stringify({ permissionKeys: parsed.data.permissionKeys }),
      actorUserId: req.auth!.userId,
    });
  }

  res.json({ ok: true });
});

export default router;
