import type { SelectQueryBuilder, ObjectLiteral } from 'typeorm';
import { applyListFilters } from './booking-list-filters';

/** Minimal query builder that records every andWhere call. */
function fakeQb() {
  const calls: Array<{ sql: string; params?: Record<string, unknown> }> = [];
  const qb = {
    andWhere: (sql: string, params?: Record<string, unknown>) => {
      calls.push({ sql, params });
      return qb;
    },
  };
  return { qb: qb as unknown as SelectQueryBuilder<ObjectLiteral>, calls };
}

describe('applyListFilters', () => {
  it('adds nothing without filters', () => {
    const { qb, calls } = fakeQb();
    applyListFilters(qb, undefined);
    applyListFilters(qb, {});
    expect(calls).toHaveLength(0);
  });

  it('filters by bill (selling) currency as a bound parameter', () => {
    const { qb, calls } = fakeQb();
    applyListFilters(qb, { sellingCurrencyId: 'cur-usd' });
    expect(calls).toEqual([
      {
        sql: 'b.selling_currency_id = :sellingCurrencyId',
        params: { sellingCurrencyId: 'cur-usd' },
      },
    ]);
  });

  it('markup applied = any markup field > 0; none = negation', () => {
    const applied = fakeQb();
    applyListFilters(applied.qb, { markup: 'applied' });
    expect(applied.calls[0].sql).toContain('b.markup_amount > 0');
    expect(applied.calls[0].sql).toContain('b.hotel_markup > 0');
    expect(applied.calls[0].sql.startsWith('NOT')).toBe(false);

    const none = fakeQb();
    applyListFilters(none.qb, { markup: 'none' });
    expect(none.calls[0].sql.startsWith('NOT (')).toBe(true);
  });

  it('filters by markup type', () => {
    const { qb, calls } = fakeQb();
    applyListFilters(qb, { markupType: 'percentage' });
    expect(calls[0]).toEqual({
      sql: 'b.markup_type = :markupType',
      params: { markupType: 'percentage' },
    });
  });

  it('splits comma-separated payment statuses into an IN list', () => {
    const { qb, calls } = fakeQb();
    applyListFilters(qb, { paymentStatus: 'UNPAID,PARTIAL' });
    expect(calls[0]).toEqual({
      sql: 'b.payment_status IN (:...paymentStatuses)',
      params: { paymentStatuses: ['UNPAID', 'PARTIAL'] },
    });
  });

  it('maps guaranteed yes/no to a boolean', () => {
    const yes = fakeQb();
    applyListFilters(yes.qb, { guaranteed: 'yes' });
    expect(yes.calls[0].params).toEqual({ guaranteed: true });
    const no = fakeQb();
    applyListFilters(no.qb, { guaranteed: 'no' });
    expect(no.calls[0].params).toEqual({ guaranteed: false });
  });

  it('matches a sales rep inside the query sales_team array', () => {
    const { qb, calls } = fakeQb();
    applyListFilters(qb, { salesUserId: 'user-1' });
    expect(calls[0].sql).toContain('jsonb_array_elements_text(q.sales_team)');
    expect(calls[0].params).toEqual({ salesUserId: 'user-1' });
  });

  it('created date range includes the whole end day', () => {
    const { qb, calls } = fakeQb();
    applyListFilters(qb, { createdFrom: '2026-11-01', createdTo: '2026-11-18' });
    expect(calls[0]).toEqual({
      sql: 'b.created_at >= :createdFrom',
      params: { createdFrom: '2026-11-01' },
    });
    expect(calls[1].sql).toContain("INTERVAL '1 day'");
    expect(calls[1].params).toEqual({ createdTo: '2026-11-18' });
  });

  it('never filters on tenant itself — tenant scoping stays in the base query', () => {
    // Cross-tenant guard: the extra filters must not add or override a
    // tenant condition (the base list query binds b.tenant_id from CLS).
    const { qb, calls } = fakeQb();
    applyListFilters(qb, {
      sellingCurrencyId: 'c',
      markup: 'applied',
      markupType: 'amount',
      paymentStatus: 'PAID',
      guaranteed: 'yes',
      salesUserId: 'u',
      createdFrom: '2026-01-01',
      createdTo: '2026-12-31',
    });
    for (const c of calls) {
      expect(c.sql).not.toMatch(/tenant_id/);
      expect(Object.keys(c.params ?? {})).not.toContain('tenantId');
    }
  });
});
