import "server-only";

import type { RowDataPacket } from "mysql2/promise";
import { unstable_cache } from "next/cache";

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

type RepresentativeCountRow = RowDataPacket & {
  total: number;
};

const getCachedRepresentativeCount = unstable_cache(
  async () => {
    const [rows] = await getDbPool().query<RepresentativeCountRow[]>(
      `
        SELECT COUNT(DISTINCT d.user_id) + 1300 AS total
        FROM domains d
        INNER JOIN users u ON u.id = d.user_id
        WHERE d.mailcow_cleanup_at IS NULL
          AND LOWER(d.domain) <> 'officialsite.kr'
          AND d.domain LIKE '%.%'
          AND LOWER(u.email) NOT LIKE '%@officialsite.kr'
      `,
    );

    return Math.max(0, Number(rows[0]?.total ?? 0));
  },
  ["public-representative-account-count-v1"],
  { revalidate: 300 },
);

export async function getPublicRepresentativeAccountCount() {
  try {
    return await getCachedRepresentativeCount();
  } catch {
    // The public page must remain available during a temporary database outage.
    return null;
  }
}
