import { and, asc, eq } from 'drizzle-orm';
import { crmReportDefinitions } from '@/db/schema';
import { db } from '@/lib/db';
import { getActiveOptionsByCategory } from '@/features/foundation/master-options/service';
import type { ReportRegistryRow, ResolvedReportContext } from '../types';

export async function listReportRegistry(
  context: ResolvedReportContext
): Promise<ReportRegistryRow[]> {
  const [rows, categoryOptions] = await Promise.all([
    db
      .select()
      .from(crmReportDefinitions)
      .where(
        and(
          eq(crmReportDefinitions.organizationId, context.organizationId),
          eq(crmReportDefinitions.isActive, true)
        )
      )
      .orderBy(asc(crmReportDefinitions.category), asc(crmReportDefinitions.name)),
    getActiveOptionsByCategory('crm_report_category', {
      organizationId: context.organizationId
    })
  ]);
  const categoryMap = new Map(
    categoryOptions.flatMap((item) => [
      [item.id, item.label] as const,
      [item.code, item.label] as const
    ])
  );

  return rows.map((row) => ({
    id: row.id,
    code: row.code,
    name: row.name,
    description: row.description,
    category: row.category,
    categoryLabel: categoryMap.get(row.category) ?? row.category,
    isSystem: row.isSystem,
    isActive: row.isActive
  }));
}
