import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { getCurrentAdminUserId } from "@/lib/auth";

export const ADMIN_ROLES = [
  { value: "super_admin", label: "Super Admin", description: "Complete system control — everything, including users, roles, and settings" },
  { value: "admin", label: "Admin", description: "Business administration — products, orders, customers, inventory, reports" },
  { value: "sales_staff", label: "Sales Staff", description: "Sales & customers — customers, orders, product prices" },
  { value: "inventory_staff", label: "Inventory Staff", description: "Stock management — products, stock in/out, adjustments, warehouses" },
  { value: "production_staff", label: "Customization / Production Staff", description: "Customized products — custom orders, design approval, production" },
  { value: "accounts_staff", label: "Accounts Staff", description: "Finance — payments, invoices, financial reports" },
  { value: "dispatch_staff", label: "Order & Dispatch Staff", description: "Order fulfilment — order processing, shipping, tracking" },
] as const;

export type AdminRole = (typeof ADMIN_ROLES)[number]["value"];

export const RESOURCES = [
  { value: "orders", label: "Orders" },
  { value: "products", label: "Products" },
  { value: "categories", label: "Categories" },
  { value: "inventory", label: "Inventory" },
  { value: "customers", label: "Customers" },
  { value: "custom_orders", label: "Custom Orders" },
  { value: "discounts", label: "Discounts & Offers" },
  { value: "payments", label: "Payments" },
  { value: "shipping", label: "Shipping" },
  { value: "marketing", label: "Marketing" },
  { value: "reviews", label: "Reviews" },
  { value: "support", label: "Support" },
  { value: "reports", label: "Reports" },
  { value: "pages", label: "Website / Pages" },
  { value: "seo", label: "SEO" },
  { value: "settings", label: "Settings" },
] as const;

export type Resource = (typeof RESOURCES)[number]["value"];

export const PERMISSION_ACTIONS = ["view", "add", "edit", "delete", "approve", "export", "print"] as const;
export type PermAction = (typeof PERMISSION_ACTIONS)[number];

const ACTION_COLUMN: Record<PermAction, "canView" | "canAdd" | "canEdit" | "canDelete" | "canApprove" | "canExport" | "canPrint"> = {
  view: "canView",
  add: "canAdd",
  edit: "canEdit",
  delete: "canDelete",
  approve: "canApprove",
  export: "canExport",
  print: "canPrint",
};

/**
 * Default permission matrix, seeded into RolePermission by prisma/seed-permissions.mjs.
 * super_admin is intentionally absent — it's granted everything unconditionally in hasPermission/getCurrentAdminRole,
 * so it can never be accidentally locked out by a seeding gap.
 * Roles/resources not listed here are fully denied (no row = no access).
 */
export const DEFAULT_PERMISSIONS: Record<Exclude<AdminRole, "super_admin">, Partial<Record<Resource, PermAction[]>>> = {
  admin: {
    orders: ["view", "add", "edit", "export", "print"],
    products: ["view", "add", "edit", "delete", "export"],
    categories: ["view", "add", "edit", "delete"],
    inventory: ["view", "add", "edit", "export"],
    customers: ["view", "add", "edit", "export"],
    custom_orders: ["view", "add", "edit", "approve", "export"],
    discounts: ["view", "add", "edit", "delete"],
    payments: ["view", "approve", "export"],
    shipping: ["view", "add", "edit", "delete"],
    marketing: ["view", "add", "edit", "delete", "approve"],
    reviews: ["view", "edit", "delete", "approve"],
    support: ["view", "edit"],
    reports: ["view", "export", "print"],
    pages: ["view", "add", "edit", "delete"],
    seo: ["view", "add", "edit"],
  },
  sales_staff: {
    customers: ["view", "add", "edit"],
    orders: ["view", "add", "edit", "print"],
    products: ["view", "edit"],
    discounts: ["view"],
    reports: ["view"],
  },
  inventory_staff: {
    products: ["view", "edit"],
    inventory: ["view", "add", "edit"],
    orders: ["view"],
  },
  production_staff: {
    custom_orders: ["view", "add", "edit", "approve"],
    products: ["view"],
  },
  accounts_staff: {
    payments: ["view", "edit", "approve", "export", "print"],
    orders: ["view", "print"],
    reports: ["view", "export", "print"],
  },
  dispatch_staff: {
    orders: ["view", "edit", "print"],
    shipping: ["view", "edit"],
  },
};

/** super_admin (and the legacy shared-password login) always pass; everything else is looked up in RolePermission. */
export async function hasPermission(role: AdminRole, resource: Resource, action: PermAction): Promise<boolean> {
  if (role === "super_admin") return true;
  const row = await prisma.rolePermission.findUnique({ where: { role_resource: { role, resource } } });
  if (!row) return false;
  return row[ACTION_COLUMN[action]];
}

/**
 * The legacy shared-password login (session userId "legacy" or missing) is treated as super_admin — it predates
 * per-user accounts and was always full-access, so it must stay that way. A real userId whose AdminUser row is
 * gone (e.g. deleted while their session was still valid) resolves to null — no permissions — rather than
 * silently failing open.
 */
export async function getCurrentAdminRole(): Promise<AdminRole | null> {
  const userId = await getCurrentAdminUserId();
  if (!userId || userId === "legacy") return "super_admin";
  const user = await prisma.adminUser.findUnique({ where: { id: userId } });
  if (!user) return null;
  return user.role as AdminRole;
}

/** Soft check for conditionally showing/hiding UI (e.g. a Delete button) — never throws or redirects. */
export async function can(resource: Resource, action: PermAction): Promise<boolean> {
  const role = await getCurrentAdminRole();
  if (!role) return false;
  return hasPermission(role, resource, action);
}

/** Hard gate for a layout or the start of a mutating server action — redirects to /iv-manage-84x2/access-denied if not permitted. */
export async function requirePermission(resource: Resource, action: PermAction = "view"): Promise<void> {
  const allowed = await can(resource, action);
  if (!allowed) redirect(`/iv-manage-84x2/access-denied?resource=${resource}`);
}
