import { prisma } from "@/lib/prisma";

export async function getLatestPlan(roomId: string, userId: string) {
  const plan = await prisma.weekendPlan.findFirst({
    where: { roomId, userId, status: "accepted" },
    orderBy: { createdAt: "desc" },
    select: { id: true, planData: true, endTime: true, createdAt: true },
  });

  if (!plan) return { plan: null };
  const parsed = JSON.parse(plan.planData);
  return {
    plan: { id: plan.id, days: parsed.days, endTime: plan.endTime, createdAt: plan.createdAt },
  };
}

export async function getPendingPlans(userId: string) {
  const plans = await prisma.weekendPlan.findMany({
    where: {
      userId,
      status: "accepted",
      endTime: { not: null, lt: new Date() },
    },
    orderBy: { createdAt: "desc" },
    select: {
      id: true,
      planData: true,
      createdAt: true,
      room: { select: { name: true, code: true } },
    },
    take: 5,
  });

  const result = plans.map((p) => {
    const parsed = JSON.parse(p.planData);
    const days = parsed.days as { date: string; items: { activity: string }[] }[];
    return {
      id: p.id,
      roomName: p.room?.name ?? "未知房间",
      roomCode: p.room?.code ?? "",
      date: days.map((d) => d.date).join(" + "),
      activities: days.flatMap((d) => d.items.map((i) => i.activity)),
      createdAt: p.createdAt,
    };
  });

  return { pending: result };
}

export async function getHistoryPlans(userId: string) {
  const plans = await prisma.weekendPlan.findMany({
    where: {
      userId,
      status: { in: ["completed", "expired"] },
    },
    orderBy: { createdAt: "desc" },
    select: {
      id: true,
      planData: true,
      status: true,
      createdAt: true,
      room: { select: { name: true, code: true } },
    },
    take: 50,
  });

  const result = plans.map((p) => {
    const parsed = JSON.parse(p.planData);
    const days = parsed.days as { date: string; items: { activity: string }[] }[];
    return {
      id: p.id,
      status: p.status,
      roomName: p.room?.name ?? "未知房间",
      roomCode: p.room?.code ?? "",
      date: days.map((d) => d.date).join(" + "),
      dayCount: days.length,
      activities: days.flatMap((d) => d.items.map((i) => i.activity)),
      createdAt: p.createdAt,
    };
  });

  return { history: result };
}
