import { Role, type BugModule } from '@prisma/client';
import { prismaUnscoped as db } from '../../lib/prisma';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';

/**
 * Where a bug is filed (docs/bug-tracker-plan.md, D4).
 *
 * The tracker is for HostelCare only, so the apps are a fixed list in the
 * code; the modules are a list the super admin edits. An archived module is
 * hidden from new reports and keeps its bugs.
 */

export const BUG_APPS = [
  { key: 'WEB_APP', label: 'Web app' },
  { key: 'ANDROID_APP', label: 'Android app' },
  { key: 'IOS_APP', label: 'iOS app' },
  { key: 'API', label: 'API' },
  { key: 'WEBSITE', label: 'Website' },
] as const;
export type BugAppKey = (typeof BUG_APPS)[number]['key'];

/** HostelCare's parts, as the team names them. The super admin can change the list. */
const STARTER_MODULES = [
  'Sign-in and account',
  'Onboarding and setup',
  'Properties and rooms',
  'Residents',
  'Stays and bookings',
  'Billing and payments',
  'Expenses',
  'Mess',
  'Gate and visitors',
  'Attendance and leave',
  'Notices and messages',
  'Requests and complaints',
  'Staff and roles',
  'Reports',
  'Inventory and laundry',
  'Enterprise',
  'Super admin and plans',
  'CRM',
  'Website and blog',
  'Other',
];

export const MODULE_NAME = { min: 2, max: 60 } as const;
const MAX_MODULES = 100;

/** A fresh tracker starts with HostelCare's modules; an edited list is never touched. */
async function ensureStarterModules() {
  if (await db.bugModule.count()) return;
  await db.bugModule.createMany({ data: STARTER_MODULES.map((name, i) => ({ name, sortOrder: i })), skipDuplicates: true });
}

async function developerNames(ids: (string | null)[]): Promise<Map<string, string>> {
  const unique = [...new Set(ids.filter((v): v is string => !!v))];
  if (!unique.length) return new Map();
  const rows = await db.user.findMany({ where: { id: { in: unique } }, select: { id: true, name: true } });
  return new Map(rows.map((r) => [r.id, r.name]));
}

function shape(m: BugModule, names: Map<string, string>) {
  return {
    id: m.id,
    name: m.name,
    sortOrder: m.sortOrder,
    archived: !!m.archivedAt,
    defaultDeveloper: m.defaultDeveloperId ? { id: m.defaultDeveloperId, name: names.get(m.defaultDeveloperId) ?? 'Unknown' } : null,
  };
}

export type PresentedModule = ReturnType<typeof shape>;

export async function listModules(opts: { includeArchived?: boolean } = {}): Promise<PresentedModule[]> {
  await ensureStarterModules();
  const rows = await db.bugModule.findMany({
    where: opts.includeArchived ? {} : { archivedAt: null },
    orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
  });
  const names = await developerNames(rows.map((r) => r.defaultDeveloperId));
  return rows.map((r) => shape(r, names));
}

async function load(id: string): Promise<BugModule> {
  const m = await db.bugModule.findUnique({ where: { id } });
  if (!m) throw new NotFoundError('Module not found.');
  return m;
}

/** Names are unique whatever their capitals: "Billing" and "billing" are one module. */
async function assertNameFree(name: string, exceptId?: string) {
  const clash = await db.bugModule.findFirst({ where: { name: { equals: name, mode: 'insensitive' }, ...(exceptId ? { id: { not: exceptId } } : {}) }, select: { archivedAt: true } });
  if (clash) throw new ConflictError(clash.archivedAt ? 'An archived module already has that name. Restore it instead.' : 'A module with that name already exists.', 'MODULE_NAME_TAKEN');
}

async function assertActiveDeveloper(id: string | null | undefined) {
  if (!id) return;
  const u = await db.user.findFirst({ where: { id, role: Role.DEVELOPER, deactivatedAt: null }, select: { id: true } });
  if (!u) throw new BadRequestError('Choose a developer whose account is switched on.', 'NOT_A_DEVELOPER');
}

async function present(id: string) {
  const m = await load(id);
  return shape(m, await developerNames([m.defaultDeveloperId]));
}

export async function createModule(input: { name: string; defaultDeveloperId?: string | null }) {
  await ensureStarterModules();
  if ((await db.bugModule.count()) >= MAX_MODULES) throw new ConflictError(`A tracker can have at most ${MAX_MODULES} modules. Archive or rename one instead.`, 'TOO_MANY_MODULES');
  await assertNameFree(input.name);
  await assertActiveDeveloper(input.defaultDeveloperId);
  const last = await db.bugModule.aggregate({ _max: { sortOrder: true } });
  const created = await db.bugModule.create({
    data: { name: input.name, defaultDeveloperId: input.defaultDeveloperId ?? null, sortOrder: (last._max.sortOrder ?? -1) + 1 },
  });
  return present(created.id);
}

export async function updateModule(id: string, input: { name?: string; defaultDeveloperId?: string | null; archived?: boolean }) {
  const m = await load(id);
  if (input.name !== undefined && input.name !== m.name) await assertNameFree(input.name, id);
  if (input.defaultDeveloperId !== undefined) await assertActiveDeveloper(input.defaultDeveloperId);
  await db.bugModule.update({
    where: { id },
    data: {
      ...(input.name !== undefined ? { name: input.name } : {}),
      ...(input.defaultDeveloperId !== undefined ? { defaultDeveloperId: input.defaultDeveloperId } : {}),
      ...(input.archived !== undefined ? { archivedAt: input.archived ? (m.archivedAt ?? new Date()) : null } : {}),
    },
  });
  return present(id);
}

/** The order the modules are offered in: the ids, first to last. */
export async function reorderModules(ids: string[]) {
  const rows = await db.bugModule.findMany({ select: { id: true } });
  const known = new Set(rows.map((r) => r.id));
  if (new Set(ids).size !== ids.length || ids.some((id) => !known.has(id))) throw new BadRequestError('That order names a module that does not exist, or one twice.', 'BAD_ORDER');
  await db.$transaction(ids.map((id, i) => db.bugModule.update({ where: { id }, data: { sortOrder: i } })));
  return listModules({ includeArchived: true });
}
