import { q as query } from '../../chunks/db_Du3AmLCY.mjs';
import { a as getUserFromRequest } from '../../chunks/user-auth_D4NBmYxs.mjs';
export { renderers } from '../../renderers.mjs';

const GET = async ({ request }) => {
  const user = getUserFromRequest(request);
  if (!user) return new Response(JSON.stringify({ error: "Niet ingelogd" }), { status: 401 });
  const result = await query(`
    SELECT w.id, w.product_id, w.target_price, w.notify_price_drop, w.notify_back_in_stock, w.created_at,
           p.name, p.brand, p.slug, p.image_url, p.cutout_image_url, p.colorway,
           (SELECT MIN(po.price) FROM product_offers po WHERE po.product_id = p.id AND po.in_stock = true) as lowest_price,
           (SELECT COUNT(*) FROM product_offers po WHERE po.product_id = p.id AND po.in_stock = true) as shop_count,
           p.original_price
    FROM watchlist w
    JOIN products p ON p.id = w.product_id
    WHERE w.user_id = $1
    ORDER BY w.created_at DESC
  `, [user.id]);
  return new Response(JSON.stringify({ items: result.rows }), {
    headers: { "Content-Type": "application/json" }
  });
};
const POST = async ({ request }) => {
  const user = getUserFromRequest(request);
  if (!user) return new Response(JSON.stringify({ error: "Niet ingelogd" }), { status: 401 });
  const { product_id, target_price } = await request.json();
  if (!product_id) return new Response(JSON.stringify({ error: "product_id verplicht" }), { status: 400 });
  await query(
    `INSERT INTO watchlist (user_id, product_id, target_price)
     VALUES ($1, $2, $3)
     ON CONFLICT (user_id, product_id) DO NOTHING`,
    [user.id, product_id, target_price || null]
  );
  return new Response(JSON.stringify({ ok: true }));
};
const PUT = async ({ request }) => {
  const user = getUserFromRequest(request);
  if (!user) return new Response(JSON.stringify({ error: "Niet ingelogd" }), { status: 401 });
  const { product_id, target_price } = await request.json();
  if (!product_id) return new Response(JSON.stringify({ error: "product_id verplicht" }), { status: 400 });
  await query(
    "UPDATE watchlist SET target_price = $1 WHERE user_id = $2 AND product_id = $3",
    [target_price || null, user.id, product_id]
  );
  return new Response(JSON.stringify({ ok: true }));
};
const DELETE = async ({ request }) => {
  const user = getUserFromRequest(request);
  if (!user) return new Response(JSON.stringify({ error: "Niet ingelogd" }), { status: 401 });
  const { product_id } = await request.json();
  if (!product_id) return new Response(JSON.stringify({ error: "product_id verplicht" }), { status: 400 });
  await query("DELETE FROM watchlist WHERE user_id = $1 AND product_id = $2", [user.id, product_id]);
  return new Response(JSON.stringify({ ok: true }));
};

const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  DELETE,
  GET,
  POST,
  PUT
}, Symbol.toStringTag, { value: 'Module' }));

const page = () => _page;

export { page };
