// app/api/appapis/wishlist/route.ts
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
import { ResultSetHeader, RowDataPacket } from 'mysql2';

interface TokenInterface {
  id: number;
  userId?: number;
  email?: string;
  role?: string;
}

// Handle OPTIONS for CORS preflight
export async function OPTIONS() {
  return NextResponse.json({}, { 
    status: 200
  });
}

export async function GET(request: NextRequest) {
  const connection = await pool.getConnection();

  try {
    // Get token from Authorization header
    const authHeader = request.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({
        success: false,
        message: "No valid authorization header found"
      }, { 
        status: 401
      });
    }

    const token = authHeader.substring(7);
    
    // Verify token
    const authResult = await verifyAuthentication(token);
    
    if (authResult instanceof NextResponse) {
      return authResult;
    }
    
    const decoded = authResult as TokenInterface;
    
    if (!decoded || !decoded.id) {
      return NextResponse.json({
        success: false,
        message: "Invalid token - no user ID found"
      }, { 
        status: 401
      });
    }

    const userId = decoded.id;

    // Check if user is student or consultant
    const [checkUser] = await connection.query<RowDataPacket[]>(
      "SELECT * FROM users WHERE id = ? AND user_type IN ('student', 'consultant')",
      [userId]
    );

    if (checkUser.length === 0) {
      return NextResponse.json(
        {
          success: false,
          message: "You are not authorized to perform this action"
        },
        { status: 401 }
      );
    }

    // Get wishlist with course and university details - FIXED QUERY
    const query = `
      SELECT 
        w.id, 
        w.user_id, 
        w.course_id, 
        w.university_id,
        w.created_at,
        w.updated_at,
        
        -- Course details
        c.id AS course_db_id,
        c.name AS course_name,
        c.slug AS course_slug,
        c.yearly_fee AS course_fee,
        c.duration_qty AS course_duration_qty,
        c.duration_type AS course_duration_type,
        c.university_id AS course_university_id,
        
        -- University details (for courses)
        cu.id AS course_university_id,
        cu.name AS course_university_name,
        cu.slug AS course_university_slug,
        cu.logo AS course_university_logo,
        cu.city AS course_university_city,
        cu.country AS course_university_country,
        
        -- University details (for direct university wishlist items)
        ud.id AS university_db_id,
        ud.name AS university_name, 
        ud.slug AS university_slug,
        ud.address AS university_address,
        ud.logo AS university_logo,
        ud.city AS university_city,
        ud.country AS university_country,
        ud.website AS university_website,
        ud.ranking AS university_ranking,
        ud.acceptance_rate AS university_acceptance_rate,
        ud.average_course_fee AS university_average_fee,
        
        -- Determine item type
        CASE 
          WHEN w.course_id IS NOT NULL THEN 'course'
          WHEN w.university_id IS NOT NULL THEN 'university'
          ELSE 'unknown'
        END AS item_type
        
      FROM wishlist w
      
      -- Join for courses
      LEFT JOIN courses c ON w.course_id = c.id
      
      -- Join for course's university
      LEFT JOIN university_details cu ON c.university_id = cu.id
      
      -- Join for direct university wishlist items
      LEFT JOIN university_details ud ON w.university_id = ud.id
      
      WHERE w.user_id = ?
      ORDER BY w.created_at DESC
    `;

    const [result] = await connection.query<RowDataPacket[]>(query, [userId]);

    // Transform the data to make it easier to use on frontend
    const transformedData = result.map(item => {
      if (item.item_type === 'course') {
        return {
          id: item.id,
          user_id: item.user_id,
          course_id: item.course_id,
          university_id: null,
          created_at: item.created_at,
          updated_at: item.updated_at,
          item_type: 'course',
          course: {
            id: item.course_db_id,
            name: item.course_name,
            slug: item.course_slug,
            fee: item.course_fee,
            duration_qty: item.course_duration_qty,
            duration_type: item.course_duration_type,
            university: {
              id: item.course_university_id,
              name: item.course_university_name,
              slug: item.course_university_slug,
              logo: item.course_university_logo,
              city: item.course_university_city,
              country: item.course_university_country
            }
          }
        };
      } else if (item.item_type === 'university') {
        return {
          id: item.id,
          user_id: item.user_id,
          course_id: null,
          university_id: item.university_id,
          created_at: item.created_at,
          updated_at: item.updated_at,
          item_type: 'university',
          university: {
            id: item.university_db_id,
            name: item.university_name,
            slug: item.university_slug,
            address: item.university_address,
            logo: item.university_logo,
            city: item.university_city,
            country: item.university_country,
            website: item.university_website,
            ranking: item.university_ranking,
            acceptance_rate: item.university_acceptance_rate,
            average_fee: item.university_average_fee
          }
        };
      }
      return item;
    });

    return NextResponse.json(
      {
        success: true,
        data: transformedData
      },
      { status: 200 }
    );

  } catch (err: any) {
    console.error('Wishlist GET error:', err);
    return NextResponse.json(
      {
        success: false,
        message: err.message || "Internal Server Error"
      },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}

export async function POST(request: NextRequest) {
  const connection = await pool.getConnection();

  try {
    // Get token from Authorization header
    const authHeader = request.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({
        success: false,
        message: "No valid authorization header found"
      }, { 
        status: 401
      });
    }

    const token = authHeader.substring(7);
    
    // Verify token
    const authResult = await verifyAuthentication(token);
    
    if (authResult instanceof NextResponse) {
      return authResult;
    }
    
    const decoded = authResult as TokenInterface;
    
    if (!decoded || !decoded.id) {
      return NextResponse.json({
        success: false,
        message: "Invalid token - no user ID found"
      }, { 
        status: 401
      });
    }

    const userId = decoded.id;

    // Check if user is student or consultant
    const [checkUser] = await connection.query<RowDataPacket[]>(
      "SELECT * FROM users WHERE id = ? AND user_type IN ('student', 'consultant')",
      [userId]
    );

    if (checkUser.length === 0) {
      return NextResponse.json(
        {
          success: false,
          message: "You are not authorized to perform this action"
        },
        { status: 401 }
      );
    }

    // Get the data from the request body
    const { course_id, university_id } = await request.json();

    if (!course_id && !university_id) {
      return NextResponse.json(
        { 
          success: false,
          message: 'Missing course_id or university_id' 
        },
        { status: 400 }
      );
    }

    // Check if the item already exists in the wishlist
    const [existsResult] = await connection.query<RowDataPacket[]>(
      `SELECT * FROM wishlist WHERE user_id = ? AND (course_id = ? OR university_id = ?)`,
      [userId, course_id || null, university_id || null]
    );

    if (existsResult.length > 0) {
      // If it exists, return the existing wishlist item with details
      const [existingWithDetails] = await connection.query<RowDataPacket[]>(
        `SELECT 
          w.*,
          c.name AS course_name,
          c.slug AS course_slug,
          ud.name AS university_name,
          ud.slug AS university_slug,
          ud.logo AS university_logo,
          ud.address AS university_address
         FROM wishlist w
         LEFT JOIN courses c ON w.course_id = c.id
         LEFT JOIN university_details ud ON w.university_id = ud.id
         WHERE w.id = ?`,
        [existsResult[0].id]
      );

      return NextResponse.json(
        { 
          success: true, 
          data: existingWithDetails[0],
          message: 'Item already in wishlist'
        },
        { status: 200 }
      );
    }

    // Insert the new wishlist item
    const [insertResult] = await connection.query<ResultSetHeader>(
      `INSERT INTO wishlist (user_id, course_id, university_id, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())`,
      [userId, course_id || null, university_id || null]
    );

    // Get the newly inserted wishlist item with details
    const [newWishlistResult] = await connection.query<RowDataPacket[]>(
      `SELECT 
        w.*,
        c.name AS course_name,
        c.slug AS course_slug,
        c.yearly_fee AS course_fee,
        ud.name AS university_name,
        ud.slug AS university_slug,
        ud.logo AS university_logo,
        ud.address AS university_address,
        ud.city AS university_city,
        ud.country AS university_country
       FROM wishlist w
       LEFT JOIN courses c ON w.course_id = c.id
       LEFT JOIN university_details ud ON w.university_id = ud.id
       WHERE w.id = ?`,
      [insertResult.insertId]
    );

    return NextResponse.json(
      { 
        success: true, 
        data: newWishlistResult[0],
        message: 'Item added to wishlist'
      },
      { status: 200 }
    );

  } catch (err: any) {
    console.error('Wishlist POST error:', err);
    return NextResponse.json(
      {
        success: false,
        message: err.message || "Internal Server Error"
      },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}

export async function DELETE(request: NextRequest) {
  const connection = await pool.getConnection();

  try {
    // Get token from Authorization header
    const authHeader = request.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({
        success: false,
        message: "No valid authorization header found"
      }, { 
        status: 401
      });
    }

    const token = authHeader.substring(7);
    
    // Verify token
    const authResult = await verifyAuthentication(token);
    
    if (authResult instanceof NextResponse) {
      return authResult;
    }
    
    const decoded = authResult as TokenInterface;
    
    if (!decoded || !decoded.id) {
      return NextResponse.json({
        success: false,
        message: "Invalid token - no user ID found"
      }, { 
        status: 401
      });
    }

    const userId = decoded.id;

    // Check if user is student or consultant
    const [checkUser] = await connection.query<RowDataPacket[]>(
      "SELECT * FROM users WHERE id = ? AND user_type IN ('student', 'consultant')",
      [userId]
    );

    if (checkUser.length === 0) {
      return NextResponse.json(
        {
          success: false,
          message: "You are not authorized to perform this action"
        },
        { status: 401 }
      );
    }

    // Get the data from the request body
    const { course_id, university_id } = await request.json();

    if (!course_id && !university_id) {
      return NextResponse.json(
        { 
          success: false,
          message: 'Missing course_id or university_id' 
        },
        { status: 400 }
      );
    }

    // Delete the wishlist entry
    const [result] = await connection.query<ResultSetHeader>(
      'DELETE FROM wishlist WHERE user_id = ? AND (course_id = ? OR university_id = ?)',
      [userId, course_id || null, university_id || null]
    );

    if (result.affectedRows === 0) {
      return NextResponse.json(
        {
          success: false,
          message: "Item not found in wishlist"
        },
        { status: 404 }
      );
    }

    return NextResponse.json(
      { 
        success: true,
        message: 'Item removed from wishlist'
      },
      { status: 200 }
    );

  } catch (err: any) {
    console.error('Wishlist DELETE error:', err);
    return NextResponse.json(
      {
        success: false,
        message: err.message || "Internal Server Error"
      },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}