import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily } from "@/lib/auth";

export async function GET() {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });
  const userId = auth.session!.userId!;

  const rows = await sql`
    SELECT rp.*, COUNT(pc.id)::int as click_count
    FROM recommended_products rp
    JOIN member_profiles mp ON mp.id = rp.profile_id
    LEFT JOIN product_clicks pc ON pc.product_id = rp.id
    WHERE mp.user_id = ${userId} AND rp.is_active = true
    GROUP BY rp.id
    ORDER BY rp.display_order ASC
  `;
  return NextResponse.json({ items: rows });
}

export async function POST(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });
  const userId = auth.session!.userId!;

  const profiles = await sql`SELECT id FROM member_profiles WHERE user_id = ${userId} LIMIT 1`;
  if (!profiles[0]) return NextResponse.json({ error: "Profile not set up yet" }, { status: 400 });
  const profileId = profiles[0].id;

  const { title, description, url, image_url, category, display_order } = await request.json();
  if (!title || !url) return NextResponse.json({ error: "title and url required" }, { status: 400 });

  const rows = await sql`
    INSERT INTO recommended_products (profile_id, title, description, url, image_url, category, display_order)
    VALUES (${profileId}, ${title}, ${description ?? null}, ${url}, ${image_url ?? null}, ${category ?? "general"}, ${display_order ?? 0})
    RETURNING *
  `;
  return NextResponse.json({ product: rows[0] });
}
