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

async function createDatabaseConnection() {
  return await createConnection({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
  });
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<any>
) {
  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Metoda není povolena' });
  }

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

    if (!session?.user?.email) {
      return res.status(401).json({ error: 'Nejste přihlášen' });
    }

    const connection = await createDatabaseConnection();

    // Zjistíme user ID podle emailu
    const [userRows] = await connection.execute(
      'SELECT id FROM users WHERE email = ?',
      [session.user.email]
    );

    if ((userRows as any[]).length === 0) {
      await connection.end();
      return res.status(404).json({ error: 'Uživatel nenalezen' });
    }

    const userId = (userRows as any[])[0].id;

    // Načteme dostupné kupony pro tohoto uživatele
    // Kupon je dostupný pokud:
    // - je napojený na user_id
    // - je aktivní (is_active = 1)
    // - ještě nebyl použit (used_count < usage_limit)
    // - ještě nevypršel (expires_at > NOW())
    const [coupons] = await connection.execute(
      `SELECT 
        code,
        discount_type,
        discount_value,
        usage_limit,
        used_count,
        expires_at,
        order_id
       FROM coupons
       WHERE user_id = ? AND is_active = 1 AND used_count < usage_limit AND expires_at > NOW()
       ORDER BY expires_at ASC`,
      [userId]
    );

    await connection.end();

    const couponList = (coupons as any[]).map(coupon => ({
      code: coupon.code,
      discountType: coupon.discount_type,
      discountValue: typeof coupon.discount_value === 'string'
        ? parseFloat(coupon.discount_value)
        : coupon.discount_value,
      usageLimit: coupon.usage_limit,
      usedCount: coupon.used_count,
      expiresAt: coupon.expires_at,
      orderId: coupon.order_id,
    }));

    return res.status(200).json({
      success: true,
      coupons: couponList,
    });
  } catch (error) {
    console.error('Chyba při načítání dostupných kuponů:', error);
    return res.status(500).json({
      error: 'Chyba při načítání dostupných kuponů',
    });
  }
}
