import { CrmActivityType, Prisma } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { ConflictError, NotFoundError } from '../../lib/errors';
import type { Actor } from './crm-users.service';
import { notify } from './crm-notify';
import { crmUrl } from './crm-mail';

/**
 * CRM lists: hand-picked groups of contacts — a campaign, a city, an event.
 *
 * Names are unique regardless of case. Deleting a list removes the grouping
 * only; its contacts stay. Counts leave out contacts in the bin. Adding and
 * removing members is written to each contact's timeline.
 *
 * Self-contained on purpose (no import from the contacts service), so the
 * contacts service can call into it for bulk actions without a cycle.
 */

export const LIST_COLORS = ['blue', 'green', 'amber', 'red', 'purple', 'pink', 'teal', 'slate'] as const;
export type ListColor = (typeof LIST_COLORS)[number];

const withCount = {
  _count: { select: { members: { where: { contact: { deletedAt: null } } } } },
} satisfies Prisma.CrmListInclude;

type ListRow = Prisma.CrmListGetPayload<{ include: typeof withCount }>;

const shape = ({ _count, nameKey: _k, ...l }: ListRow) => ({ ...l, contactCount: _count.members });

export async function listLists(q?: string) {
  const rows = await prismaUnscoped.crmList.findMany({
    where: q?.trim() ? { OR: [{ name: { contains: q.trim(), mode: 'insensitive' } }, { description: { contains: q.trim(), mode: 'insensitive' } }] } : {},
    orderBy: { name: 'asc' },
    take: 500,
    include: withCount,
  });
  return rows.map(shape);
}

async function load(id: string) {
  const l = await prismaUnscoped.crmList.findUnique({ where: { id }, include: withCount });
  if (!l) throw new NotFoundError('List not found');
  return l;
}

export async function getList(id: string) {
  return shape(await load(id));
}

function nameClash(e: unknown): never {
  if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
    throw new ConflictError('A list with that name already exists.', 'LIST_NAME_TAKEN');
  }
  throw e;
}

export async function createList(input: { name: string; description?: string | null; color?: ListColor }, actor: Actor) {
  const name = input.name.trim();
  const l = await prismaUnscoped.crmList
    .create({
      data: { name, nameKey: name.toLowerCase(), description: input.description?.trim() || null, color: input.color ?? 'blue', createdById: actor.id },
      include: withCount,
    })
    .catch(nameClash);
  notify({ actor, text: `${actor.name} created the list "${l.name}"`, url: crmUrl(`lists/${l.id}`), about: [] });
  return shape(l);
}

export async function updateList(id: string, input: { name?: string; description?: string | null; color?: ListColor }) {
  await load(id);
  const name = input.name?.trim();
  const l = await prismaUnscoped.crmList
    .update({
      where: { id },
      data: {
        ...(name ? { name, nameKey: name.toLowerCase() } : {}),
        ...(input.description !== undefined ? { description: input.description?.trim() || null } : {}),
        ...(input.color ? { color: input.color } : {}),
      },
      include: withCount,
    })
    .catch(nameClash);
  return shape(l);
}

export async function deleteList(id: string, actor?: Actor) {
  const l = await load(id);
  await prismaUnscoped.crmList.delete({ where: { id } });
  if (actor) notify({ actor, text: `${actor.name} deleted the list "${l.name}" (its contacts were kept)`, url: crmUrl('lists'), about: [] });
}

/** Add contacts to a list; returns how many were newly added. */
export async function addMembers(listId: string, contactIds: string[], actor: Actor) {
  const list = await load(listId);
  const live = await prismaUnscoped.crmContact.findMany({ where: { id: { in: contactIds }, deletedAt: null }, select: { id: true } });
  const already = await prismaUnscoped.crmListMember.findMany({ where: { listId, contactId: { in: live.map((c) => c.id) } }, select: { contactId: true } });
  const have = new Set(already.map((m) => m.contactId));
  const fresh = live.map((c) => c.id).filter((id) => !have.has(id));
  if (!fresh.length) return 0;
  await prismaUnscoped.$transaction([
    prismaUnscoped.crmListMember.createMany({ data: fresh.map((contactId) => ({ listId, contactId, addedById: actor.id })), skipDuplicates: true }),
    prismaUnscoped.crmActivity.createMany({
      data: fresh.map((contactId) => ({
        contactId,
        type: CrmActivityType.LIST_ADDED,
        meta: { listId, listName: list.name },
        actorId: actor.id,
        actorName: actor.name,
      })),
    }),
  ]);
  notify({ actor, text: `${actor.name} added ${fresh.length} contact${fresh.length === 1 ? '' : 's'} to "${list.name}"`, url: crmUrl(`lists/${listId}`), about: [] });
  return fresh.length;
}

/** Take contacts off a list; returns how many were on it. */
export async function removeMembers(listId: string, contactIds: string[], actor: Actor) {
  const list = await load(listId);
  const on = await prismaUnscoped.crmListMember.findMany({ where: { listId, contactId: { in: contactIds } }, select: { contactId: true } });
  if (!on.length) return 0;
  const ids = on.map((m) => m.contactId);
  await prismaUnscoped.$transaction([
    prismaUnscoped.crmListMember.deleteMany({ where: { listId, contactId: { in: ids } } }),
    prismaUnscoped.crmActivity.createMany({
      data: ids.map((contactId) => ({
        contactId,
        type: CrmActivityType.LIST_REMOVED,
        meta: { listId, listName: list.name },
        actorId: actor.id,
        actorName: actor.name,
      })),
    }),
  ]);
  notify({ actor, text: `${actor.name} removed ${ids.length} contact${ids.length === 1 ? '' : 's'} from "${list.name}"`, url: crmUrl(`lists/${listId}`), about: [] });
  return ids.length;
}
