import type { SelectQueryBuilder, ObjectLiteral } from 'typeorm';

/** Booking list filters — shared by the list, its Excel export and the
 *  controller (one shape so a new filter is added in one place). */
export interface BookingListFilters {
  status?: string;
  destinationId?: string;
  sourceId?: string;
  dateFrom?: string;
  dateTo?: string;
  sellingCurrencyId?: string;
  markup?: 'applied' | 'none';
  markupType?: 'amount' | 'percentage';
  /** Comma-separated BookingPaymentStatus values. */
  paymentStatus?: string;
  guaranteed?: 'yes' | 'no';
  salesUserId?: string;
  createdFrom?: string;
  createdTo?: string;
}

/** Markup set on any part of the booking's markup config. */
const MARKUP_APPLIED_SQL =
  '(b.markup_amount > 0 OR b.hotel_markup > 0 OR b.transport_markup > 0 OR b.activity_markup > 0 OR b.special_markup > 0)';

/**
 * Bill currency, markup, payment, guarantee, sales rep and created-date
 * filters for the booking list (aliases: `b` = booking, `q` = query).
 * Values are bound as parameters — never interpolated — and the DTO
 * whitelists the enum-like ones.
 */
export function applyListFilters<T extends ObjectLiteral>(
  qb: SelectQueryBuilder<T>,
  filters?: BookingListFilters,
): void {
  if (!filters) return;
  if (filters.sellingCurrencyId)
    qb.andWhere('b.selling_currency_id = :sellingCurrencyId', {
      sellingCurrencyId: filters.sellingCurrencyId,
    });
  if (filters.markup === 'applied') qb.andWhere(MARKUP_APPLIED_SQL);
  else if (filters.markup === 'none') qb.andWhere(`NOT ${MARKUP_APPLIED_SQL}`);
  if (filters.markupType)
    qb.andWhere('b.markup_type = :markupType', { markupType: filters.markupType });
  if (filters.paymentStatus) {
    const paymentStatuses = filters.paymentStatus.split(',').filter(Boolean);
    if (paymentStatuses.length > 0)
      qb.andWhere('b.payment_status IN (:...paymentStatuses)', { paymentStatuses });
  }
  if (filters.guaranteed)
    qb.andWhere('b.is_guaranteed = :guaranteed', { guaranteed: filters.guaranteed === 'yes' });
  if (filters.salesUserId)
    qb.andWhere(
      'EXISTS (SELECT 1 FROM jsonb_array_elements_text(q.sales_team) st WHERE st = :salesUserId)',
      { salesUserId: filters.salesUserId },
    );
  if (filters.createdFrom)
    qb.andWhere('b.created_at >= :createdFrom', { createdFrom: filters.createdFrom });
  if (filters.createdTo)
    // Inclusive of the whole end day.
    qb.andWhere("b.created_at < (CAST(:createdTo AS date) + INTERVAL '1 day')", {
      createdTo: filters.createdTo,
    });
}
