import type { Repository } from 'typeorm';
import type { ClsService } from 'nestjs-cls';
import { ActivityPricingRepository, LIVE_TICKET_CONDITION } from './activity-pricing.repository';
import type { ActivityPricingEntity } from '../../../entities/activity-pricing.entity';

/**
 * Regression: deleting an activity soft-deletes the activity (and its
 * tickets) but not its activity_pricing rows, so the Pricing → Activities
 * page kept listing it. Every list read must join the activity with
 * `is_deleted = false` and drop rows of deleted tickets.
 */

type Call = { method: string; args: unknown[] };

/** Chainable QueryBuilder stand-in that records every call in order. */
function fakeQb(calls: Call[], result: { rawOne?: unknown; rawMany?: unknown[] } = {}) {
  const qb: Record<string, unknown> = {};
  const chain = [
    'where',
    'andWhere',
    'innerJoin',
    'innerJoinAndSelect',
    'leftJoin',
    'leftJoinAndSelect',
    'select',
    'addSelect',
    'groupBy',
    'orderBy',
    'addOrderBy',
    'offset',
    'limit',
  ];
  for (const m of chain) {
    qb[m] = jest.fn((...args: unknown[]) => {
      calls.push({ method: m, args });
      return qb;
    });
  }
  qb.clone = jest.fn(() => qb);
  qb.getRawOne = jest.fn(async () => result.rawOne);
  qb.getRawMany = jest.fn(async () => result.rawMany ?? []);
  qb.getMany = jest.fn(async () => []);
  return qb;
}

function expectLiveActivityFilter(calls: Call[]) {
  const whereIdx = calls.findIndex((c) => c.method === 'where');
  const joinIdx = calls.findIndex(
    (c) =>
      (c.method === 'innerJoin' || c.method === 'innerJoinAndSelect') &&
      c.args[0] === 'ap.activity' &&
      c.args[2] === 'activity.is_deleted = false',
  );
  const ticketIdx = calls.findIndex(
    (c) => c.method === 'andWhere' && c.args[0] === LIVE_TICKET_CONDITION,
  );
  expect(joinIdx).toBeGreaterThanOrEqual(0);
  expect(ticketIdx).toBeGreaterThanOrEqual(0);
  // `.where()` replaces earlier conditions, so the filter must come after it.
  expect(ticketIdx).toBeGreaterThan(whereIdx);
  // A later `.where()` would wipe the ticket filter.
  expect(calls.slice(ticketIdx).some((c) => c.method === 'where')).toBe(false);
}

describe('ActivityPricingRepository — hides deleted activities', () => {
  const TENANT = 'tenant-a';
  let builders: Call[][];
  let results: { rawOne?: unknown; rawMany?: unknown[] }[];
  let repo: ActivityPricingRepository;

  beforeEach(() => {
    builders = [];
    results = [];
    const orm = {
      createQueryBuilder: jest.fn(() => {
        const calls: Call[] = [];
        builders.push(calls);
        return fakeQb(calls, results.shift());
      }),
    } as unknown as Repository<ActivityPricingEntity>;
    const cls = {
      get: jest.fn((_key: string) => TENANT),
    } as unknown as ClsService;
    repo = new ActivityPricingRepository(orm, cls);
  });

  it('paginated list (Pricing → Activities page) filters list and count', async () => {
    results.push({ rawOne: { cnt: '1' }, rawMany: [{ activity_id: 'act-1' }] });
    await repo.findPaginatedByActivities({ page: 1, limit: 10 });
    expect(builders).toHaveLength(2);
    expectLiveActivityFilter(builders[0]); // activity ids + count
    expectLiveActivityFilter(builders[1]); // pricing rows for that page
  });

  it('search uses the live activity join', async () => {
    results.push({ rawOne: { cnt: '0' }, rawMany: [] });
    await repo.findPaginatedByActivities({ search: 'Palm' });
    expectLiveActivityFilter(builders[0]);
    expect(builders[0]).toContainEqual({
      method: 'andWhere',
      args: ['activity.name ILIKE :search', { search: '%Palm%' }],
    });
  });

  it('destination/currency lookup filters deleted activities', async () => {
    await repo.findByDestinationAndCurrency('dest-1', 'cur-1');
    expectLiveActivityFilter(builders[0]);
  });

  it('Excel sample export filters deleted activities', async () => {
    await repo.findAllForExport('dest-1');
    expectLiveActivityFilter(builders[0]);
  });
});

describe('LIVE_TICKET_CONDITION', () => {
  it('drops rows of deleted tickets', () => {
    expect(LIVE_TICKET_CONDITION).toContain(
      'ap.ticket_id IS NOT NULL AND ticket.is_deleted = false',
    );
  });

  it('drops the leftover "General" (no-ticket) row once the activity has live tickets', () => {
    expect(LIVE_TICKET_CONDITION).toContain('ap.ticket_id IS NULL AND NOT EXISTS');
    expect(LIVE_TICKET_CONDITION).toContain(
      'live_t.activity_id = ap.activity_id AND live_t.is_deleted = false',
    );
  });
});
