// lib/repository/entity-resolver.ts
// Session-scoped in-memory cache for entity name resolution.
// Avoids repeated Supabase round-trips when rendering many document rows.

import type { SupabaseClient } from '@supabase/supabase-js'

interface SupplierInfo  { id: string; supplier_number: string; supplier_name: string; supplier_location: string | null }
interface DeptInfo      { id: string; department_code: string; department_name: string }
interface ProjectInfo   { id: string; supplier_name: string; visit_date: string; product_name: string | null }

const supplierCache  = new Map<string, SupplierInfo>()
const deptCache      = new Map<string, DeptInfo>()
const projectCache   = new Map<string, ProjectInfo>()

export function invalidateEntityCache() {
  supplierCache.clear()
  deptCache.clear()
  projectCache.clear()
}

export async function resolveSuppliers(
  ids: string[],
  supabase: SupabaseClient
): Promise<SupplierInfo[]> {
  const missing = ids.filter((id) => !supplierCache.has(id))
  if (missing.length > 0) {
    const { data } = await supabase
      .from('supplier_master_data')
      .select('id, supplier_number, supplier_name, supplier_location')
      .in('id', missing)
    for (const row of data ?? []) {
      supplierCache.set(row.id as string, row as SupplierInfo)
    }
  }
  return ids.map((id) => supplierCache.get(id)).filter(Boolean) as SupplierInfo[]
}

export async function resolveDepartments(
  ids: string[],
  supabase: SupabaseClient
): Promise<DeptInfo[]> {
  const missing = ids.filter((id) => !deptCache.has(id))
  if (missing.length > 0) {
    const { data } = await supabase
      .from('department_master_data')
      .select('id, department_code, department_name')
      .in('id', missing)
    for (const row of data ?? []) {
      deptCache.set(row.id as string, row as DeptInfo)
    }
  }
  return ids.map((id) => deptCache.get(id)).filter(Boolean) as DeptInfo[]
}

export async function resolveProject(
  id: string,
  supabase: SupabaseClient
): Promise<ProjectInfo | null> {
  if (projectCache.has(id)) return projectCache.get(id)!
  const { data } = await supabase
    .from('projects')
    .select('id, supplier_name, visit_date, product_name')
    .eq('id', id)
    .maybeSingle()
  if (data) {
    projectCache.set(id, data as ProjectInfo)
    return data as ProjectInfo
  }
  return null
}
