import { Router } from "express";
import { prisma } from "@stamp/shared";
import { optionalAuth, requireAuth } from "../middleware/auth.js";

const router = Router();

router.get("/", optionalAuth, async (req, res) => {
  const stamps = await prisma.stamp.findMany({
    where: { enabled: true },
    orderBy: { sortOrder: "asc" },
  });

  let collections: Set<string> = new Set();
  let collectionMap: Map<string, Date> = new Map();

  if (req.userId) {
    const userCollections = await prisma.collection.findMany({
      where: { userId: req.userId },
      select: { stampId: true, collectedAt: true },
    });
    userCollections.forEach((c) => {
      collections.add(c.stampId);
      collectionMap.set(c.stampId, c.collectedAt);
    });
  }

  const data = stamps.map((s) => ({
    id: s.id,
    name: s.name,
    note: s.note,
    imageColor: s.imageColor,
    imageGrey: s.imageGrey,
    sortOrder: s.sortOrder,
    collected: collections.has(s.id),
    collectedAt: collectionMap.get(s.id)?.toISOString() ?? null,
  }));

  res.json({ success: true, data });
});

router.get("/:id", async (req, res) => {
  const stamp = await prisma.stamp.findUnique({ where: { id: req.params.id } });
  if (!stamp) {
    res.status(404).json({ success: false, error: { code: "NOT_FOUND", message: "图章不存在" } });
    return;
  }
  res.json({
    success: true,
    data: {
      id: stamp.id,
      name: stamp.name,
      note: stamp.note,
      imageColor: stamp.imageColor,
      imageGrey: stamp.imageGrey,
      sortOrder: stamp.sortOrder,
    },
  });
});

router.post("/:id/collect", requireAuth, async (req, res) => {
  const stamp = await prisma.stamp.findUnique({ where: { id: req.params.id, enabled: true } });
  if (!stamp) {
    res.status(404).json({ success: false, error: { code: "NOT_FOUND", message: "图章不存在" } });
    return;
  }

  const existing = await prisma.collection.findUnique({
    where: { userId_stampId: { userId: req.userId!, stampId: stamp.id } },
  });
  if (existing) {
    res.status(409).json({ success: false, error: { code: "ALREADY_COLLECTED", message: "你已经收集了这枚图章" } });
    return;
  }

  const collection = await prisma.collection.create({
    data: { userId: req.userId!, stampId: stamp.id },
  });

  res.json({
    success: true,
    data: { id: collection.id, stampId: collection.stampId, collectedAt: collection.collectedAt.toISOString() },
  });
});

export default router;
