import { PrismaMssql } from "@prisma/adapter-mssql";
import { PrismaClient } from "./generated/prisma/client";

const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
  throw new Error("DATABASE_URL is not set.");
}

const prisma = new PrismaClient({
  adapter: new PrismaMssql(connectionString),
});

try {
  const rowSummary = await prisma.$queryRawUnsafe<
    Array<{ total_rows: number; distinct_configs: number }>
  >(`
    SELECT
      COUNT(*) AS total_rows,
      COUNT(DISTINCT Config_RecID) AS distinct_configs
    FROM dbo.Config_User_Defined_Field_Value;
  `);

  const relatedRowCounts = await prisma.$queryRawUnsafe<
    Array<{
      config_rows: number;
      cs_result_detail_rows: number;
      config_custom_field_nonempty: number;
    }>
  >(`
    SELECT
      (SELECT COUNT(*) FROM dbo.Config) AS config_rows,
      (SELECT COUNT(*) FROM dbo.CS_Result_Detail) AS cs_result_detail_rows,
      (SELECT COUNT(*)
       FROM dbo.Config
       WHERE Custom_Field IS NOT NULL
         AND LEN(LTRIM(RTRIM(CONVERT(nvarchar(max), Custom_Field)))) > 0) AS config_custom_field_nonempty;
  `);

  const topConfigs = await prisma.$queryRawUnsafe<
    Array<{ config_recid: number; field_count: number }>
  >(`
    SELECT TOP 10
      Config_RecID AS config_recid,
      COUNT(*) AS field_count
    FROM dbo.Config_User_Defined_Field_Value
    GROUP BY Config_RecID
    ORDER BY field_count DESC, config_recid ASC;
  `);

  const customFieldSamples = await prisma.$queryRawUnsafe<
    Array<{ config_recid: number; custom_field_prefix: string }>
  >(`
    SELECT TOP 5
      Config_RecID AS config_recid,
      LEFT(CONVERT(nvarchar(max), Custom_Field), 250) AS custom_field_prefix
    FROM dbo.Config
    WHERE Custom_Field IS NOT NULL
      AND LEN(LTRIM(RTRIM(CONVERT(nvarchar(max), Custom_Field)))) > 0
    ORDER BY Config_RecID ASC;
  `);

  console.log(
    JSON.stringify(
      {
        rowSummary: rowSummary[0] ?? null,
        relatedRowCounts: relatedRowCounts[0] ?? null,
        topConfigs,
        customFieldSamples,
      },
      null,
      2,
    ),
  );
} finally {
  await prisma.$disconnect();
}
