import { NextResponse } from "next/server";
import { createClient } from "@/lib/supabase-server";
import { createAdminClient } from "@/lib/supabase-admin";
import { isOwnerUser } from "@/lib/owner-auth";

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

function normalizeBoolean(value: unknown, fallback: boolean) {
  if (typeof value === "boolean") return value;
  return fallback;
}

function normalizeNumber(value: unknown, fallback: number) {
  const n = Number(value);
  return Number.isFinite(n) ? n : fallback;
}

function normalizeIsoDate(value: unknown) {
  const text = normalizeString(value);
  if (!text) return null;
  const parsed = new Date(text);
  if (Number.isNaN(parsed.getTime())) return null;
  return parsed.toISOString();
}

function normalizePlacement(value: unknown) {
  const cleaned = normalizeString(value);
  return cleaned || "admin.meus_fornecedores.top";
}

async function ensureOwner() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user || !isOwnerUser({ id: user.id, email: user.email })) {
    return { ok: false as const, status: 403, user: null };
  }

  return { ok: true as const, status: 200, user };
}

export async function GET(request: Request) {
  const auth = await ensureOwner();
  if (!auth.ok) return NextResponse.json({ error: "Sem permissão." }, { status: auth.status });

  const { searchParams } = new URL(request.url);
  const placement = normalizeString(searchParams.get("placement") || "");
  const admin = createAdminClient();

  const query = admin
    .from("sponsored_banners")
    .select("id,placement,title,link_url,open_in_new_tab,image_url,image_alt,active,position,start_at,end_at,config,created_at,updated_at")
    .order("placement", { ascending: true })
    .order("position", { ascending: true })
    .order("created_at", { ascending: false });

  const { data, error } = placement ? await query.eq("placement", placement) : await query;
  if (error) return NextResponse.json({ error: "Não foi possível carregar os banners." }, { status: 400 });
  return NextResponse.json({ ok: true, banners: data || [] });
}

export async function POST(request: Request) {
  const auth = await ensureOwner();
  if (!auth.ok) return NextResponse.json({ error: "Sem permissão." }, { status: auth.status });

  const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
  const placement = normalizePlacement(body?.placement);
  const title = normalizeString(body?.title) || null;
  const linkUrl = normalizeString(body?.link_url) || null;
  const openInNewTab = normalizeBoolean(body?.open_in_new_tab, true);
  const imageUrl = normalizeString(body?.image_url);
  const imageAlt = normalizeString(body?.image_alt) || null;
  const active = normalizeBoolean(body?.active, true);
  const position = normalizeNumber(body?.position, 0);
  const startAt = normalizeIsoDate(body?.start_at);
  const endAt = normalizeIsoDate(body?.end_at);
  const config =
    body?.config && typeof body.config === "object" && !Array.isArray(body.config) ? (body.config as Record<string, unknown>) : {};

  if (!imageUrl) return NextResponse.json({ error: "Informe a imagem do banner." }, { status: 400 });

  const admin = createAdminClient();
  const now = new Date().toISOString();
  const { data, error } = await admin
    .from("sponsored_banners")
    .insert({
      placement,
      title,
      link_url: linkUrl,
      open_in_new_tab: openInNewTab,
      image_url: imageUrl,
      image_alt: imageAlt,
      active,
      position,
      start_at: startAt,
      end_at: endAt,
      config,
      created_at: now,
      updated_at: now,
    })
    .select("id")
    .single();

  if (error || !data?.id) return NextResponse.json({ error: "Não foi possível salvar o banner." }, { status: 400 });
  return NextResponse.json({ ok: true, id: data.id });
}

export async function PATCH(request: Request) {
  const auth = await ensureOwner();
  if (!auth.ok) return NextResponse.json({ error: "Sem permissão." }, { status: auth.status });

  const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
  const id = normalizeString(body?.id);
  if (!id) return NextResponse.json({ error: "ID inválido." }, { status: 400 });

  const payload: Record<string, unknown> = { updated_at: new Date().toISOString() };

  if (body?.placement !== undefined) payload.placement = normalizePlacement(body.placement);
  if (body?.title !== undefined) payload.title = normalizeString(body.title) || null;
  if (body?.link_url !== undefined) payload.link_url = normalizeString(body.link_url) || null;
  if (body?.open_in_new_tab !== undefined) payload.open_in_new_tab = normalizeBoolean(body.open_in_new_tab, true);
  if (body?.image_url !== undefined) payload.image_url = normalizeString(body.image_url);
  if (body?.image_alt !== undefined) payload.image_alt = normalizeString(body.image_alt) || null;
  if (body?.active !== undefined) payload.active = normalizeBoolean(body.active, true);
  if (body?.position !== undefined) payload.position = normalizeNumber(body.position, 0);
  if (body?.start_at !== undefined) payload.start_at = normalizeIsoDate(body.start_at);
  if (body?.end_at !== undefined) payload.end_at = normalizeIsoDate(body.end_at);
  if (body?.config !== undefined) {
    payload.config =
      body.config && typeof body.config === "object" && !Array.isArray(body.config) ? (body.config as Record<string, unknown>) : {};
  }

  if (payload.image_url !== undefined && !payload.image_url) {
    return NextResponse.json({ error: "Informe a imagem do banner." }, { status: 400 });
  }

  const admin = createAdminClient();
  const { error } = await admin.from("sponsored_banners").update(payload).eq("id", id);
  if (error) return NextResponse.json({ error: "Não foi possível atualizar o banner." }, { status: 400 });
  return NextResponse.json({ ok: true });
}

export async function DELETE(request: Request) {
  const auth = await ensureOwner();
  if (!auth.ok) return NextResponse.json({ error: "Sem permissão." }, { status: auth.status });

  const { searchParams } = new URL(request.url);
  const id = normalizeString(searchParams.get("id"));
  if (!id) return NextResponse.json({ error: "ID inválido." }, { status: 400 });

  const admin = createAdminClient();
  const { error } = await admin.from("sponsored_banners").delete().eq("id", id);
  if (error) return NextResponse.json({ error: "Não foi possível deletar o banner." }, { status: 400 });
  return NextResponse.json({ ok: true });
}

