import { and, eq, inArray, isNull } from 'drizzle-orm';
import { msOptions } from '@/db/schema';
import { db } from '@/lib/db';

export type OptionDisplayRecord = {
  id: string;
  category: string;
  code: string;
  label: string;
  value: string | null;
};

export async function resolveOptionLabels(input: {
  organizationId: string;
  category: string;
  optionIds: Array<string | null | undefined>;
}) {
  const uniqueIds = [...new Set(input.optionIds.filter((value): value is string => Boolean(value)))];

  if (!uniqueIds.length) {
    return new Map<string, OptionDisplayRecord>();
  }

  const rows = await db
    .select({
      id: msOptions.id,
      category: msOptions.category,
      code: msOptions.code,
      label: msOptions.label,
      value: msOptions.value
    })
    .from(msOptions)
    .where(
      and(
        eq(msOptions.organizationId, input.organizationId),
        eq(msOptions.category, input.category),
        inArray(msOptions.id, uniqueIds),
        isNull(msOptions.deletedAt)
      )
    );

  return new Map(rows.map((row) => [row.id, row]));
}
