import { NextResponse } from 'next/server';
import { pool } from '@/backend/utils/db';

interface Card {
  id: number;
  name: string;
  minSalary: number;
  annualFee: number;
  image: string;
  ccurl: string;
  points?: string[];
}

interface Category {
  id: number;
  title: string;
}

export async function GET() {
  try {
    const [categories] = await pool.query(`
      SELECT cd.idcardtype AS id, cardtypedesc AS title 
      FROM cardtypes cd
      WHERE useascategory = 1 
        AND EXISTS (
          SELECT 1 FROM creditcardstypes ct WHERE ct.idcardtype = cd.idcardtype
        )
    `);

    const result = await Promise.all(
      (categories as Category[]).map(async (category) => {
        const [cards] = await pool.query(
          `
          SELECT DISTINCT
            cc.idcreditcards AS id,
            cc.creditcardsname AS name,
            cc.MinimumSalary AS minSalary,
            cc.AnnualFee AS annualFee,
            CONCAT('/cardimages/', cc.creditcardsimagename) AS image
            ,cc.ccurl
          FROM creditcards cc
          INNER JOIN creditcardstypes ct ON ct.idcreditcards = cc.idcreditcards
          WHERE ct.idcardtype = ?
        `,
          [category.id]
        );

        const cardsWithPoints = await Promise.all(
          (cards as Card[]).map(async (card) => {
            try {
              const [points] = await pool.query(
                `
                SELECT creditcardshortfeature AS point
                FROM creditcardsfetures
                WHERE idcreditcards = ?
              `,
                [card.id]
              );

              return {
                ...card,
                points: (points as { point: string }[]).map((p) => p.point),
              };
            } catch (err) {
              console.error(`Error fetching points for card ID ${card.id}:`, err);
              return { ...card, points: [] };
            }
          })
        );

        return {
          title: category.title,
          cards: cardsWithPoints,
        };
      })
    );

    return NextResponse.json(result);
  } catch (error) {
    console.error('API error:', error);
    return NextResponse.json(
      { success: false, error: (error as Error).message },
      { status: 500 }
    );
  }
}
