import type { NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, ERR } from "@/lib/api-response";

type ArtistRow = Awaited<ReturnType<typeof prisma.artist.findMany>>[number];

/**
 * GET /api/artists
 * 列出所有候选艺人（含当前票数 / 排名）。
 *
 * Query:
 *   - sort: 'votes' (default) | 'no' | 'recent'
 *   - tag:  ArtistTag · 单标签筛选
 *   - q:    搜索关键词（按 name / enName / no 模糊）
 */
export async function GET(req: NextRequest) {
  try {
    const sp = req.nextUrl.searchParams;
    const sort = (sp.get("sort") ?? "votes") as "votes" | "no" | "recent";
    const tag = sp.get("tag");
    const q = sp.get("q")?.trim();

    const orderBy =
      sort === "no"
        ? { no: "asc" as const }
        : sort === "recent"
          ? { updatedAt: "desc" as const }
          : [
              { voteCount: "desc" as const },
              { no: "asc" as const },
            ];

    let artists: ArtistRow[] = await prisma.artist.findMany({
      where: {
        status: "ACTIVE",
        ...(q && {
          OR: [
            { name: { contains: q } },
            { enName: { contains: q } },
            { no: { contains: q } },
          ],
        }),
      },
      orderBy,
    });

    // tag 过滤在内存做（tags 是 JSON 列）
    if (tag) {
      artists = artists.filter((a: ArtistRow) => {
        const tags = Array.isArray(a.tags) ? (a.tags as string[]) : [];
        return tags.includes(tag);
      });
    }

    return ok({ artists, total: artists.length });
  } catch (e) {
    console.error("[GET /api/artists]", e);
    return ERR.INTERNAL();
  }
}
