import { NextResponse } from "next/server";
import { createAdminClient, createClient } from "@/lib/supabase-server";

type SystemNoticeRow = {
  id: string;
  scope: string;
  title: string | null;
  message: string;
  variant: string;
  dismiss_mode: string;
  active: boolean;
  position: number;
  start_at: string | null;
  end_at: string | null;
  show_on_paths: string[] | null;
  hide_on_paths: string[] | null;
  theme: Record<string, unknown> | null;
  updated_at: string | null;
};

function normalizeString(value: unknown) {
  return typeof value === "string" ? value.trim() : "";
}

function shouldShowOnPath(pathname: string, showOnPaths: string[] | null, hideOnPaths: string[] | null) {
  const clean = String(pathname || "/").trim() || "/";
  if (Array.isArray(hideOnPaths) && hideOnPaths.some((p) => p && clean.startsWith(p))) return false;
  if (Array.isArray(showOnPaths) && showOnPaths.length) return showOnPaths.some((p) => p && clean.startsWith(p));
  return true;
}

export async function GET(request: Request) {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    return NextResponse.json({ error: "Não autenticado." }, { status: 401 });
  }

  const { searchParams } = new URL(request.url);
  const pathname = normalizeString(searchParams.get("path") || "/");
  const scope = "admin";
  const now = Date.now();

  const admin = createAdminClient();
  const { data, error } = await admin
    .from("system_notices")
    .select("id,scope,title,message,variant,dismiss_mode,active,position,start_at,end_at,show_on_paths,hide_on_paths,theme,updated_at")
    .eq("active", true)
    .in("scope", ["all", scope])
    .order("position", { ascending: true })
    .order("created_at", { ascending: false })
    .limit(20);

  if (error) return NextResponse.json({ error: "Não foi possível carregar as tarjas." }, { status: 400 });

  const rows = (Array.isArray(data) ? (data as SystemNoticeRow[]) : []).filter((row) => {
    const startAt = row.start_at ? new Date(row.start_at).getTime() : null;
    const endAt = row.end_at ? new Date(row.end_at).getTime() : null;
    if (startAt && Number.isFinite(startAt) && now < startAt) return false;
    if (endAt && Number.isFinite(endAt) && now > endAt) return false;
    return shouldShowOnPath(pathname, row.show_on_paths ?? null, row.hide_on_paths ?? null);
  });

  return NextResponse.json({ notices: rows });
}
