import { NextResponse, type NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { getStaffSession } from "@/lib/staff-session";

export async function GET(request: NextRequest) {
  const url = new URL(request.url);
  const search = url.searchParams.get("search")?.toLowerCase();
  const type = url.searchParams.get("type");
  const take = Number(url.searchParams.get("limit") || 50);

  const where: any = {};
  if (type) where.type = type;
  if (search) {
    where.OR = [
      { url: { contains: search, mode: "insensitive" } },
      { alt: { contains: search, mode: "insensitive" } },
      { tags: { has: search } },
    ];
  }

  const assets = await prisma.media_assets.findMany({
    where,
    orderBy: { createdAt: "desc" },
    take,
  });

  return NextResponse.json({ data: assets });
}

export async function POST(request: NextRequest) {
  const user = await getStaffSession();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await request.json().catch(() => ({}));
  const { url, alt, type, width, height, tags } = body;

  if (!url || !alt || !type) {
    return NextResponse.json(
      { error: "url, alt, and type are required" },
      { status: 400 },
    );
  }

  const record = await prisma.media_assets.create({
    data: {
      url,
      alt,
      type,
      width: width ?? null,
      height: height ?? null,
      tags: Array.isArray(tags) ? tags : [],
      uploadedBy: user.id,
    },
  });

  return NextResponse.json({ data: record });
}
