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

function isValidSlug(slug: string) {
  return /^[a-z0-9-]{3,40}$/.test(slug);
}

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 * FROM member_profiles WHERE user_id = ${userId} LIMIT 1`;
  return NextResponse.json({ profile: rows[0] ?? null });
}

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

  const { slug, display_name, bio, avatar_url, is_public } = await request.json();
  if (!slug || !display_name) return NextResponse.json({ error: "slug and display_name required" }, { status: 400 });
  if (!isValidSlug(slug)) return NextResponse.json({ error: "Slug must be 3–40 lowercase letters, numbers, or hyphens" }, { status: 400 });

  const rows = await sql`
    INSERT INTO member_profiles (user_id, family_id, slug, display_name, bio, avatar_url, is_public, updated_at)
    VALUES (${userId}, ${familyId}, ${slug}, ${display_name}, ${bio ?? null}, ${avatar_url ?? null}, ${is_public ?? false}, now())
    ON CONFLICT (user_id) DO UPDATE SET
      slug = EXCLUDED.slug,
      display_name = EXCLUDED.display_name,
      bio = EXCLUDED.bio,
      avatar_url = EXCLUDED.avatar_url,
      is_public = EXCLUDED.is_public,
      updated_at = now()
    RETURNING *
  `;
  return NextResponse.json({ profile: rows[0] });
}
