import type { UrlCodec } from '@/lib/url/useUrlFilterState';

export type VendorDealsTab = 'active' | 'pending' | 'closed' | 'history' | 'drafts';
export type VendorDealsClosedFilter = 'all' | 'won' | 'partial' | 'lost';

const VALID_TABS = new Set<VendorDealsTab>(['active', 'pending', 'closed', 'history', 'drafts']);
const VALID_CLOSED = new Set<VendorDealsClosedFilter>(['all', 'won', 'partial', 'lost']);
const DEFAULT_TAB: VendorDealsTab = 'active';
const DEFAULT_CLOSED: VendorDealsClosedFilter = 'all';

function parseTab(raw: string | null): VendorDealsTab {
  if (raw && VALID_TABS.has(raw as VendorDealsTab)) return raw as VendorDealsTab;
  return DEFAULT_TAB;
}

function parseClosed(raw: string | null): VendorDealsClosedFilter {
  if (raw && VALID_CLOSED.has(raw as VendorDealsClosedFilter))
    return raw as VendorDealsClosedFilter;
  return DEFAULT_CLOSED;
}

export interface VendorDealsUrlState extends Record<string, unknown> {
  tab: VendorDealsTab;
  closed: VendorDealsClosedFilter;
}

export function makeVendorDealsCodec(basePath: string): UrlCodec<VendorDealsUrlState> {
  return {
    parse(loc) {
      const sp = new URLSearchParams(loc.search);
      return {
        tab: parseTab(sp.get('tab')),
        closed: parseClosed(sp.get('closed')),
      };
    },

    build(state) {
      const sp = new URLSearchParams();
      if (state.tab !== DEFAULT_TAB) sp.set('tab', state.tab);
      if (state.closed !== DEFAULT_CLOSED) sp.set('closed', state.closed);
      const qs = sp.toString();
      return qs ? `${basePath}?${qs}` : basePath;
    },
  };
}
