/**
 * CM-1: client-groups service — CRUD, wipe-and-rewrite membership, member
 * email resolution (for copy-emails), and the port-scope guard.
 */
import { describe, it, expect } from 'vitest';

import { db } from '@/lib/db';
import { clientContacts } from '@/lib/db/schema';
import {
  archiveClientGroup,
  createClientGroup,
  getClientGroupById,
  listClientGroups,
  listGroupMembers,
  setGroupMembers,
  updateClientGroup,
} from '@/lib/services/client-groups.service';
import { makeAuditMeta, makeClient, makePort } from '../helpers/factories';

describe('client-groups.service (CM-1)', () => {
  it('creates a group and lists it with a zero member count', async () => {
    const port = await makePort();
    const meta = makeAuditMeta({ portId: port.id });
    const group = await createClientGroup(port.id, { name: 'VIP Mailing' }, meta);
    expect(group.name).toBe('VIP Mailing');
    expect(group.color).toBe('#6B7280');

    const list = await listClientGroups(port.id);
    expect(list).toHaveLength(1);
    expect(list[0]?.memberCount).toBe(0);
  });

  it('sets members (wipe-and-rewrite) and lists them with primary email', async () => {
    const port = await makePort();
    const meta = makeAuditMeta({ portId: port.id });
    const c1 = await makeClient({ portId: port.id });
    const c2 = await makeClient({ portId: port.id });
    await db
      .insert(clientContacts)
      .values({ clientId: c1.id, channel: 'email', value: 'vip@example.com', isPrimary: true });

    const group = await createClientGroup(port.id, { name: 'Newsletter' }, meta);
    await setGroupMembers(group.id, port.id, [c1.id, c2.id], meta);

    const members = await listGroupMembers(group.id, port.id);
    expect(members.map((m) => m.clientId).sort()).toEqual([c1.id, c2.id].sort());
    expect(members.find((m) => m.clientId === c1.id)?.email).toBe('vip@example.com');
    expect(members.find((m) => m.clientId === c2.id)?.email).toBeNull();

    const list = await listClientGroups(port.id);
    expect(list.find((g) => g.id === group.id)?.memberCount).toBe(2);

    // Wipe-and-rewrite: setting to [c2] drops c1.
    await setGroupMembers(group.id, port.id, [c2.id], meta);
    const after = await listGroupMembers(group.id, port.id);
    expect(after.map((m) => m.clientId)).toEqual([c2.id]);
  });

  it('rejects members from a foreign port', async () => {
    const portA = await makePort();
    const portB = await makePort();
    const meta = makeAuditMeta({ portId: portA.id });
    const foreign = await makeClient({ portId: portB.id });
    const group = await createClientGroup(portA.id, { name: 'Scoped' }, meta);
    await expect(setGroupMembers(group.id, portA.id, [foreign.id], meta)).rejects.toThrow(
      /not in this port/,
    );
  });

  it('updates and archives a group', async () => {
    const port = await makePort();
    const meta = makeAuditMeta({ portId: port.id });
    const group = await createClientGroup(port.id, { name: 'Temp' }, meta);
    const updated = await updateClientGroup(group.id, port.id, { name: 'Renamed' }, meta);
    expect(updated.name).toBe('Renamed');

    await archiveClientGroup(group.id, port.id, meta);
    await expect(getClientGroupById(group.id, port.id)).rejects.toThrow(/not found/i);
    expect(await listClientGroups(port.id)).toHaveLength(0);
  });
});
