import { hasValue, utc } from '@finalytic/utils';
import type { listing_bool_exp } from '../gqty';

export function whereListingIsActive(): listing_bool_exp {
  return {
    _or: [
      {
        // LEGACY teams
        tenant: {
          isGeneralLedger: { _eq: false },
        },
        calculatedStatus: { _eq: 'active' },
      },
      {
        // GL teams
        tenant: {
          isGeneralLedger: { _eq: true },
        },
        ...whereGlListingIsActive(undefined, utc().yyyymmdd()),
      },
    ],
  };
}

export function whereGlListingIsActive(
  where?: listing_bool_exp,
  date: string = utc().yyyymmdd(),
  includeUpcoming = false
): listing_bool_exp {
  const statusWhere = {
    _or: [
      {
        _not: {
          ownershipPeriods: {},
        },
      },
      {
        _not: whereGlListingIsInactive(undefined, date, includeUpcoming),
      },
    ],
  } satisfies listing_bool_exp;

  if (where) return { _and: [statusWhere, where] };

  return statusWhere;
}

export const whereGlListingIsInactive = (
  where?: listing_bool_exp,
  date: string = utc().yyyymmdd(),
  includeUpcoming = false
): listing_bool_exp => {
  const statusWhere = {
    ownershipPeriods: {
      setListingInactive: { _eq: true },
      _or: [
        includeUpcoming
          ? {
              startAt: {
                _gte: date,
              },
            }
          : undefined,
        {
          startAt: {
            _lt: date,
          },
          endAt: {
            _gte: date,
          },
        },
        {
          startAt: {
            _lt: date,
          },
          endAt: {
            _is_null: true,
          },
        },
      ].filter(hasValue),
    },
  } satisfies listing_bool_exp;

  if (where) return { _and: [statusWhere, where] };

  return statusWhere;
};
