import type { Database } from 'bun:sqlite';

/** Row shape used by the change detector (subset of groups columns). */
export interface GroupRow {
  id: string;
  active: number;
  archived: number;
  is_community: number;
  name?: string | null;
}

export interface GroupChanges {
  newlyActivated: string[];
  newlyDeactivated: Array<{ id: string; name: string | null }>;
}

/**
 * Compare before/after snapshots of the groups table and detect:
 *  - Groups that became active (new or reactivated, excluding communities/archived)
 *  - Groups that went from active → inactive (excluding communities/archived)
 */
export function detectGroupChanges(
  before: GroupRow[],
  after: GroupRow[]
): GroupChanges {
  const beforeMap = new Map<string, GroupRow>();
  for (const r of before) beforeMap.set(String(r.id), r);

  const afterMap = new Map<string, GroupRow>();
  for (const r of after) afterMap.set(String(r.id), r);

  const newlyActivated: string[] = [];
  for (const [id, a] of afterMap) {
    const b = beforeMap.get(id);
    const active =
      Number(a.active) === 1 &&
      Number(a.archived) === 0 &&
      Number(a.is_community) === 0;
    if (active && (!b || Number(b.active) !== 1)) {
      newlyActivated.push(id);
    }
  }

  const newlyDeactivated: Array<{ id: string; name: string | null }> = [];
  for (const [id, b] of beforeMap) {
    const a = afterMap.get(id);
    if (!a) continue;
    if (
      Number(b.active) === 1 &&
      Number(a.active) === 0 &&
      Number(a.archived) === 0 &&
      Number(a.is_community) === 0 &&
      Number(b.is_community) === 0
    ) {
      newlyDeactivated.push({ id, name: a.name ?? b.name ?? null });
    }
  }

  return { newlyActivated, newlyDeactivated };
}
