import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { LojaVitrine } from "./LojaVitrine";

export const metadata = { title: "Loja" };

export default async function LojaPage() {
  const session = await getServerSession(authOptions);
  const usuarioId = (session?.user as any)?.id;

  // Busca alunos do responsável e fardamentos da unidade
  const [responsabilidades, fardamentosRaw] = await Promise.all([
    prisma.alunoResponsavel.findMany({
      where: { usuarioId },
      include: {
        aluno: {
          include: {
            turma: { select: { nome: true } },
            unidade: { select: { nome: true } },
          },
        },
      },
    }),
    prisma.fardamento.findMany({
      where: { ativo: true },
      include: {
        tamanhos: {
          where: { ativo: true, estoque: { gt: 0 } },
          orderBy: { tamanho: "asc" },
        },
        unidade: { select: { nome: true } },
      },
      orderBy: [{ destaque: "desc" }, { nome: "asc" }],
    }),
  ]);

  // MySQL armazena imagens como Json — normaliza para string[]
  const fardamentos = fardamentosRaw.map((f) => ({
    ...f,
    imagens: (f.imagens as string[]) ?? [],
  }));

  const alunos = responsabilidades.map((r) => ({
    id: r.aluno.id,
    nome: r.aluno.nome,
    turma: r.aluno.turma?.nome,
    unidade: r.aluno.unidade.nome,
    parentesco: r.parentesco,
  }));

  return <LojaVitrine fardamentos={fardamentos} alunos={alunos} />;
}
