import type { NextApiRequest, NextApiResponse } from 'next';
import mysql from 'mysql2/promise';

interface Brand {
  id: number;
  name: string;
  slug: string;
  description: string;
  website?: string;
  image_url?: 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<Brand[] | ErrorResponse>
) {
  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

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

    const query = `
      SELECT
        b.id,
        b.name,
        b.slug,
        b.description,
        b.website,
        bi.url as image_url
      FROM brands b
      LEFT JOIN brand_images bi
        ON bi.brand_id = b.id
        AND bi.is_primary = 1
      WHERE b.is_active = 1
        AND EXISTS (
          SELECT 1
          FROM products active_product
          JOIN product_variants active_variant
            ON active_variant.product_id = active_product.id
           AND active_variant.is_active = 1
          JOIN prices active_price
            ON active_price.variant_id = active_variant.id
           AND active_price.valid_to IS NULL
          LEFT JOIN product_stock active_stock
            ON active_stock.product_id = active_product.id
          WHERE active_product.brand_id = b.id
            AND active_product.type = 'perfume'
            AND active_product.is_active = 1
            AND (
              (active_variant.kind = 'SAMPLE' AND COALESCE(active_stock.stock, 0) >= active_variant.volume_ml)
              OR (active_variant.kind <> 'SAMPLE' AND active_variant.stock > 0)
            )
        )
      ORDER BY b.name ASC
    `;

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

    res.status(200).json(rows as any[]);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch brands' });
  }
}
