import { NextResponse } from "next/server";
import { typedQuery } from "@/backend/utils/typedQuery";
import {
  defaultScrollPopupConfig,
  type ScrollPopupConfig,
} from "@/lib/scrollPopupDefaults";

export const dynamic = "force-dynamic";
export const revalidate = 0;

type ScrollPopupRow = {
  titleText: string | null;
  subtitleText: string | null;
  phonePlaceholder: string | null;
  submitButtonText: string | null;
  termsText: string | null;
  termsUrl: string | null;
};

export async function GET() {
  try {
    const [rows] = await typedQuery<ScrollPopupRow>(
      `
      SELECT
        title_text AS titleText,
        subtitle_text AS subtitleText,
        phone_placeholder AS phonePlaceholder,
        submit_button_text AS submitButtonText,
        terms_text AS termsText,
        terms_url AS termsUrl
      FROM scroll_popup_content
      WHERE is_active = 1
      ORDER BY updated_at DESC, idscroll_popup_content DESC
      LIMIT 1
      `
    );

    if (!rows.length) {
      return NextResponse.json({ config: defaultScrollPopupConfig });
    }

    const row = rows[0];
    const config: ScrollPopupConfig = {
      titleText: row.titleText ?? defaultScrollPopupConfig.titleText,
      subtitleText: row.subtitleText ?? defaultScrollPopupConfig.subtitleText,
      phonePlaceholder: row.phonePlaceholder ?? defaultScrollPopupConfig.phonePlaceholder,
      submitButtonText: row.submitButtonText ?? defaultScrollPopupConfig.submitButtonText,
      termsText: row.termsText ?? defaultScrollPopupConfig.termsText,
      termsUrl: row.termsUrl ?? defaultScrollPopupConfig.termsUrl,
    };

    return NextResponse.json({ config });
  } catch (error) {
    console.error("[ERROR] Failed to load scroll popup config:", error);
    return NextResponse.json({ config: defaultScrollPopupConfig }, { status: 200 });
  }
}
