import type { NextApiRequest, NextApiResponse } from 'next';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '../../../auth/[...nextauth]';
import mysql from 'mysql2/promise';
import { generateInvoiceHtml } from '@/lib/emailTemplates';
import { generatePdfFromHtml } from '@/lib/pdf';

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<any | ErrorResponse>
) {
  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const session = await getServerSession(req, res, authOptions);

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

  const { id } = req.query;

  if (!id || Array.isArray(id)) {
    return res.status(400).json({ error: 'Invalid order ID' });
  }

  let connection: any = null;

  try {
    connection = await pool.getConnection();

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

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

    const userId = userRows[0].id;

    // Fetch order
    const [orderRows]: any = await connection.query(
      `SELECT o.id, o.order_number, o.created_at, o.total_price, o.discount_amount, o.is_gift_wrapped
       FROM orders o
       WHERE o.id = ? AND o.user_id = ?`,
      [id, userId]
    );

    if (!orderRows || orderRows.length === 0) {
      connection.release();
      return res.status(404).json({ error: 'Order not found' });
    }

    const order = orderRows[0];

    // Fetch order items
    const [items]: any = await connection.query(
      `SELECT oi.product_name, oi.brand, oi.quantity, oi.unit_price, oi.total_price, p.type as product_type, pv.volume_ml
       FROM order_items oi
       LEFT JOIN products p ON p.id = oi.product_id
       LEFT JOIN product_variants pv ON pv.id = oi.variant_id
       WHERE oi.order_id = ?`,
      [order.id]
    );

    // Fetch shipping info
    const [shippingRows]: any = await connection.query(
      `SELECT method_name, price FROM order_shipping WHERE order_id = ?`,
      [order.id]
    );

    let shippingMethod = 'Neznámá';
    let shippingPrice = 0;

    if (shippingRows && shippingRows.length > 0) {
      shippingMethod = shippingRows[0].method_name || 'Neznámá';
      shippingPrice = parseFloat(String(shippingRows[0].price)) || 0;
    }

    // Fetch billing address
    const [addressRows]: any = await connection.query(
      `SELECT full_name, street, city, zip, phone, email FROM order_addresses
       WHERE order_id = ? AND address_type = 'billing'
       LIMIT 1`,
      [order.id]
    );

    let customerName = '';
    let customerEmail = '';
    let customerPhone = '';
    let billingAddress: any = null;

    if (addressRows && addressRows.length > 0) {
      const addr = addressRows[0];
      customerName = addr.full_name;
      customerEmail = addr.email;
      customerPhone = addr.phone;
      billingAddress = {
        street: addr.street,
        city: addr.city,
        zip: addr.zip,
      };
    }

    // Build invoice items
    const invoiceItems = (items || [])
      .map((item: any) => {
        let itemName = item.brand ? `${item.brand} - ${item.product_name}` : item.product_name;
        // Přidáme informaci o variantě (volume)
        if (item.volume_ml) {
          itemName += ` (${item.volume_ml}ml)`;
        }
        return {
          name: itemName,
          quantity: item.quantity,
          unitPrice: parseFloat(item.unit_price),
          lineTotal: parseFloat(item.total_price),
          productType: item.product_type || 'perfume',
        };
      })
      .filter((item: { lineTotal: number }) => item.lineTotal > 0);

    // Add gift wrapping if present
    if (order.is_gift_wrapped === 1) {
      invoiceItems.push({
        name: 'Dárkové balení',
        quantity: 1,
        unitPrice: 99,
        lineTotal: 99,
      });
    }

    const invoiceData = {
      orderNumber: order.order_number,
      createdAt: new Date(order.created_at),
      items: invoiceItems,
      shippingPrice: Number(shippingPrice),
      total: Number(order.total_price),
      currency: 'Kč',
      shippingMethod,
      customerName,
      customerEmail,
      customerPhone,
      billingAddress,
      discountAmount: Number(order.discount_amount) || 0,
    };

    const invoiceHtml = generateInvoiceHtml(invoiceData);

    connection.release();

    try {
      const pdfBuffer = await generatePdfFromHtml(invoiceHtml);

      res.setHeader('Content-Type', 'application/pdf');
      res.setHeader('Content-Disposition', `attachment; filename="faktura-${order.order_number}.pdf"`);
      res.send(pdfBuffer);
    } catch (pdfError) {
      res.status(500).json({ error: 'Chyba při generování faktury' });
    }
  } catch (error) {
    if (connection) {
      try {
        connection.release();
      } catch (e) {
      }
    }
    return res.status(500).json({ error: 'Internal server error' });
  }
}
