export const prerender = false;

import type { APIRoute } from 'astro';
import { env } from 'cloudflare:workers';
import { getSession, type SessionEnv } from '../../../lib/session.js';
import { getDb, type DbEnv } from '../../../lib/db.js';
import { createStorefrontCartStore } from '../../../lib/cart-store.js';
import { type AuthEnv } from '../../../lib/auth-engine.js';
import { type StorefrontLimiterEnv } from '../../../lib/rate-limit.js';

export const POST: APIRoute = async ({ cookies, redirect }) => {
  const cfEnv = env as (AuthEnv & SessionEnv & DbEnv & StorefrontLimiterEnv) | undefined;

  const session = cfEnv ? await getSession(cfEnv, cookies) : null;
  if (!session) {
    return redirect('/login', 302);
  }

  const { db } = getDb(cfEnv!);
  const store = createStorefrontCartStore(db);

  const cart = await store.load(session.userId);
  if (cart) {
    await store.save({ ...cart, lines: [], subtotal: 0n });
  }

  return redirect('/cart', 302);
};
