import { DashboardService } from './dashboard.service';

type Audit = { id: string; entity_type: string; entity_id: string; action: string };

function build(
  audits: Audit[],
  parentRows: Record<string, Array<{ id: string; booking_id: string }>>,
) {
  const auditQb = {
    leftJoinAndSelect: jest.fn().mockReturnThis(),
    where: jest.fn().mockReturnThis(),
    orderBy: jest.fn().mockReturnThis(),
    take: jest.fn().mockReturnThis(),
    getMany: jest
      .fn()
      .mockResolvedValue(
        audits.map((a) => ({ ...a, created_at: new Date(), performer: { name: 'JAYDEEP' } })),
      ),
  };
  const rawQuery = jest.fn((sql: string) => {
    const table = Object.keys(parentRows).find((t) => sql.includes(`FROM ${t}`));
    return Promise.resolve(table ? parentRows[table] : []);
  });
  const auditRepo = { createQueryBuilder: () => auditQb, manager: { query: rawQuery } };
  const bookingQb = {
    leftJoinAndSelect: jest.fn().mockReturnThis(),
    select: jest.fn().mockReturnThis(),
    where: jest.fn().mockReturnThis(),
    getMany: jest
      .fn()
      .mockResolvedValue([{ id: 'b1', booking_number: 'MT-1', query: { guest_name: 'Kishan' } }]),
  };
  const bookingRepo = { createQueryBuilder: () => bookingQb };
  const svc = new DashboardService(
    {} as never,
    bookingRepo as never,
    {} as never,
    {} as never,
    auditRepo as never,
    {} as never,
    {} as never,
    {} as never,
  );
  const run = () =>
    (
      svc as unknown as {
        getRecentActivity(t: string): Promise<Array<Record<string, unknown>>>;
      }
    ).getRecentActivity('tenant-1');
  return { run, rawQuery };
}

describe('DashboardService.getRecentActivity — booking link', () => {
  it('links booking items and change requests to their parent booking', async () => {
    const { run } = build(
      [
        { id: 'a1', entity_type: 'booking_activity_item', entity_id: 'item-1', action: 'updated' },
        { id: 'a2', entity_type: 'change_request', entity_id: 'cr-1', action: 'created' },
        { id: 'a3', entity_type: 'booking', entity_id: 'b1', action: 'updated' },
      ],
      {
        booking_activity_items: [{ id: 'item-1', booking_id: 'b1' }],
        booking_change_requests: [{ id: 'cr-1', booking_id: 'b1' }],
      },
    );
    const rows = await run();
    for (const r of rows) {
      expect(r.booking_id).toBe('b1');
      expect(r.entity_number).toBe('MT-1');
      expect(r.guest_name).toBe('Kishan');
    }
  });

  it('no parent booking (e.g. a quote change request) → no link', async () => {
    const { run } = build(
      [{ id: 'a1', entity_type: 'change_request', entity_id: 'cr-q', action: 'created' }],
      { booking_change_requests: [] },
    );
    const [row] = await run();
    expect(row.booking_id).toBeNull();
    expect(row.entity_number).toBeNull();
  });

  it('scopes the parent lookup to the tenant (no cross-tenant read)', async () => {
    const { run, rawQuery } = build(
      [{ id: 'a1', entity_type: 'booking_transport_item', entity_id: 'item-9', action: 'updated' }],
      { booking_transport_items: [] },
    );
    await run();
    expect(rawQuery).toHaveBeenCalledTimes(1);
    const [sql, params] = rawQuery.mock.calls[0] as unknown as [string, unknown[]];
    expect(sql).toContain('tenant_id = $1');
    expect(params).toEqual(['tenant-1', ['item-9']]);
  });
});
