import type { APIRoute } from 'astro';
import { query } from '../../../lib/db';
import { getUserFromRequest } from '../../../lib/user-auth';

// GET - get user's watchlist with current prices
export const GET: APIRoute = 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' },
  });
};

// POST - add product to watchlist
export const POST: APIRoute = 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 }));
};

// PUT - update target price
export const PUT: APIRoute = 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 }));
};

// DELETE - remove from watchlist
export const DELETE: APIRoute = 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 }));
};
