// 모모유통 공급자(supplier) 정보 — DB(momo_statement_branches) 기반
// 거래명세표/계산서 발행 시 사용자(user_info.statement_branch) 별로 분기
//
// 관리자가 /m/admin/statement-branches 페이지에서 정보 편집 가능.
// API 요청 시마다 DB 조회하면 부담이라 60초 in-memory 캐시.

import { queryRows } from "@/lib/db";

export interface BranchSupplier {
  CODE: string;
  NAME: string;
  CEO: string;
  BANK_ACCOUNT: string;
  PHONE: string;
  EMAIL: string;
  BIZ_NO: string;
  ADDRESS: string;
}

// fallback (DB 가 비어있거나 마이그레이션 028 적용 전 환경)
const FALLBACK: Record<string, BranchSupplier> = {
  HQ: {
    CODE: "HQ",
    NAME: "모모유통",
    CEO: "이상용",
    BANK_ACCOUNT: "기업은행 434-115361-01-016 (이상용)",
    PHONE: "010-6369-8443",
    EMAIL: "momo8443@daum.net",
    BIZ_NO: "",
    ADDRESS: "",
  },
  KIMPO: {
    CODE: "KIMPO",
    NAME: "모모유통",
    CEO: "이상용",
    BANK_ACCOUNT: "농협 351-1383-7634-13 (모모유통)",
    PHONE: "010-5789-9431",
    EMAIL: "momokimpo@nate.com",
    BIZ_NO: "",
    ADDRESS: "",
  },
};

let cache: { at: number; map: Record<string, BranchSupplier> } | null = null;
const CACHE_TTL_MS = 60_000;

async function loadBranches(): Promise<Record<string, BranchSupplier>> {
  if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache.map;
  try {
    const rows = await queryRows<{
      CODE: string; NAME: string; CEO: string | null; BANK_ACCOUNT: string;
      PHONE: string | null; EMAIL: string | null; BIZ_NO: string | null; ADDRESS: string | null;
    }>(
      `SELECT code AS "CODE", name AS "NAME", ceo_name AS "CEO",
              bank_account AS "BANK_ACCOUNT", phone AS "PHONE",
              email AS "EMAIL", biz_no AS "BIZ_NO", address AS "ADDRESS"
       FROM momo_statement_branches
       WHERE COALESCE(is_del,'N') != 'Y'`
    );
    const map: Record<string, BranchSupplier> = {};
    for (const r of rows) {
      map[r.CODE] = {
        CODE: r.CODE,
        NAME: r.NAME,
        CEO: r.CEO ?? "",
        BANK_ACCOUNT: r.BANK_ACCOUNT,
        PHONE: r.PHONE ?? "",
        EMAIL: r.EMAIL ?? "",
        BIZ_NO: r.BIZ_NO ?? "",
        ADDRESS: r.ADDRESS ?? "",
      };
    }
    cache = { at: Date.now(), map: { ...FALLBACK, ...map } };
    return cache.map;
  } catch {
    return FALLBACK;
  }
}

export async function getSupplierByBranch(branch?: string | null): Promise<BranchSupplier> {
  const code = branch || "HQ";
  const map = await loadBranches();
  return map[code] ?? map.HQ ?? FALLBACK.HQ;
}

export function invalidateBranchCache() {
  cache = null;
}
