import type { NextApiRequest, NextApiResponse } from 'next';
import { getServerSession } from 'next-auth/next';
import { authOptions } from './auth/[...nextauth]';
import mysql from 'mysql2/promise';
import { resolveImageUrl } from '../../lib/images';

interface WishlistItem {
  id: number;
  productId: number;
  productName: string;
  brandName: string;
  primaryImage: string;
  variantId: number;
  variantLabel: string;
  volumeMl: string;
  currentPrice: number;
  addedAt: string;
}

interface ErrorResponse {
  error: string;
}

const pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'perfume_shop',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<WishlistItem[] | { success: boolean } | ErrorResponse>
) {
  const session = await getServerSession(req, res, authOptions);

  if (!session?.user?.email) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  try {
    const connection = await pool.getConnection();

    // Get user ID from database by email
    const [users]: any = await connection.query(
      'SELECT id FROM users WHERE email = ?',
      [session.user.email]
    );

    if (!users || users.length === 0) {
      connection.release();
      return res.status(401).json({ error: 'User not found' });
    }

    const userId = users[0].id;

    if (req.method === 'GET') {
      // Get all wishlist items for user
      const query = `
        SELECT
          wi.id,
          p.id AS productId,
          p.name AS productName,
          b.name AS brandName,
          img.url AS primaryImage,
          pv.id AS variantId,
          pv.label AS variantLabel,
          pv.volume_ml AS volumeMl,
          pr.price AS currentPrice,
          wi.created_at AS addedAt
        FROM wishlist_items wi
        JOIN products p ON p.id = wi.product_id
        JOIN brands b ON b.id = p.brand_id
        JOIN product_variants pv ON pv.id = wi.variant_id
        JOIN prices pr ON pr.variant_id = pv.id AND pr.valid_to IS NULL
        LEFT JOIN product_images img ON img.product_id = p.id AND img.is_primary = 1
        WHERE wi.user_id = ?
        ORDER BY wi.created_at DESC
      `;

      const [rows] = await connection.query(query, [userId]);
      connection.release();

      return res.status(200).json(
        (rows as WishlistItem[]).map((item) => ({
          ...item,
          primaryImage: resolveImageUrl(item.primaryImage),
        }))
      );
    }

    if (req.method === 'POST') {
      // Add item to wishlist
      const { productId, variantId } = req.body;

      if (!productId || !variantId) {
        connection.release();
        return res.status(400).json({ error: 'Missing productId or variantId' });
      }

      try {
        await connection.query(
          'INSERT INTO wishlist_items (user_id, product_id, variant_id) VALUES (?, ?, ?)',
          [userId, productId, variantId]
        );
        connection.release();
        return res.status(201).json({ success: true });
      } catch (err: any) {
        connection.release();
        // Check if it's a duplicate entry
        if (err.code === 'ER_DUP_ENTRY') {
          return res.status(409).json({ error: 'Item already in wishlist' });
        }
        throw err;
      }
    }

    if (req.method === 'DELETE') {
      // Remove item from wishlist
      const { itemId } = req.query;

      if (!itemId) {
        connection.release();
        return res.status(400).json({ error: 'Missing itemId' });
      }

      // Verify the item belongs to the user
      const [rows] = await connection.query(
        'SELECT user_id FROM wishlist_items WHERE id = ?',
        [itemId]
      );

      if (!rows || (rows as any[]).length === 0 || (rows as any[])[0].user_id !== userId) {
        connection.release();
        return res.status(403).json({ error: 'Forbidden' });
      }

      await connection.query('DELETE FROM wishlist_items WHERE id = ?', [itemId]);
      connection.release();
      return res.status(200).json({ success: true });
    }

    connection.release();
    return res.status(405).json({ error: 'Method not allowed' });
  } catch (error) {
    return res.status(500).json({ error: 'Internal server error' });
  }
}
