import { db } from "@/app/db/db";
import { asc, eq } from "drizzle-orm";
import {
  CATEGORY_TABLES,
  LANDLORD_CATEGORIES,
  type LandlordOverrideCategory,
} from "./categories";

export type { LandlordOverrideCategory } from "./categories";

export interface OverrideRow {
  description: string;
  value: string;
  source: string;
}

export type LandlordOverrideResults = Record<LandlordOverrideCategory, OverrideRow[]>;

function emptyResults(): LandlordOverrideResults {
  const out = {} as LandlordOverrideResults;
  for (const category of LANDLORD_CATEGORIES) out[category] = [];
  return out;
}

// Reads every landlord_*_overrides table for a portfolio, one query per
// category, keyed by category. The portfolio id is a bigint FK; the bulk-upload
// flow carries it as a numeric string.
export async function getLandlordOverrides(
  portfolioId: string,
): Promise<LandlordOverrideResults> {
  if (!/^\d+$/.test(portfolioId)) return emptyResults();
  const pid = BigInt(portfolioId);

  const entries = await Promise.all(
    LANDLORD_CATEGORIES.map(async (category) => {
      const { table } = CATEGORY_TABLES[category];
      const rows = (await db
        .select({
          description: table.description,
          value: table.value,
          source: table.source,
        })
        .from(table)
        .where(eq(table.portfolioId, pid))
        .orderBy(asc(table.description))) as OverrideRow[];
      return [category, rows] as const;
    }),
  );

  const out = emptyResults();
  for (const [category, rows] of entries) out[category] = rows;
  return out;
}
