Skip to content
import {
  isCardForClass,
  MAX_DECK_SIZE,
  MIN_DECK_SIZE,
} from "../../../lib/cards.ts";
import { getHero, saveHeroDeck } from "../../../lib/heroes.ts";
import { define } from "../../../utils.ts";

export const handler = define.handlers({
  async POST(ctx) {
    const user = ctx.state.user;
    if (!user) return new Response("Unauthorized", { status: 401 });
    const hero = await getHero(user.id);
    if (!hero) return Response.json({ error: "No hero." }, { status: 404 });

    let body: unknown;
    try {
      body = await ctx.req.json();
    } catch {
      return Response.json({ error: "Invalid JSON." }, { status: 400 });
    }
    const deck = (body as { deck?: unknown } | null)?.deck;
    if (!Array.isArray(deck) || deck.some((id) => typeof id !== "string")) {
      return Response.json({ error: "Invalid deck." }, { status: 400 });
    }
    if (deck.length < MIN_DECK_SIZE || deck.length > MAX_DECK_SIZE) {
      return Response.json(
        { error: `Decks require ${MIN_DECK_SIZE}-${MAX_DECK_SIZE} cards.` },
        { status: 400 },
      );
    }
    if (deck.some((id) => !isCardForClass(id, hero.class))) {
      return Response.json({ error: "That deck contains an unusable card." }, {
        status: 400,
      });
    }
    const saved = await saveHeroDeck(user.id, deck as string[]);
    if (!saved) {
      return Response.json({ error: "That deck contains unowned cards." }, {
        status: 409,
      });
    }
    return Response.json({ deck });
  },
});