// app/api/frontend/notifications/route.js
import { NextRequest, NextResponse } from "next/server";
import { verifyAuthentication } from "../../../utils/verifyAuthentication";
import { RowDataPacket } from "mysql2";
import pool from "../../../../lib/db/db";

export async function GET(request: NextRequest) {
  try {
    const token = request.cookies.get("university-token")?.value || null;
    const decoded = await verifyAuthentication(token);

    if (decoded instanceof NextResponse || !decoded) {
      return NextResponse.json(
        { success: false, message: "Unauthorized" },
        { status: 401 }
      );
    }

    // Get notifications for this user
    const [notifications] = await pool.query<RowDataPacket[]>(
      `SELECT 
        id, type, name, email, message, 
        user_id, university_id, consultant_id, student_id,
        application_id, is_read, created_at,
        UNIX_TIMESTAMP(created_at) as timestamp
      FROM notifications 
      WHERE user_id = ? 
      ORDER BY created_at DESC 
      LIMIT 50`,
      [decoded.id]
    );

    // Mark notifications as read
    await pool.query(
      `UPDATE notifications 
       SET is_read = 1 
       WHERE user_id = ? AND is_read = 0`,
      [decoded.id]
    );

    // Format the notifications
    const formattedNotifications = notifications.map(notification => {
      let title = '';
      let description = notification.message || '';
      let iconType = 'info';
      
      // Determine notification type and title
      switch(notification.type) {
        case 'university':
          title = 'University Update';
          iconType = 'university';
          break;
        case 'application':
          title = 'Application Update';
          iconType = 'application';
          break;
        case 'student':
          title = 'Student Inquiry';
          iconType = 'student';
          break;
        case 'system':
          title = 'System Notification';
          iconType = 'system';
          break;
        case 'email':
          title = 'New Message';
          iconType = 'email';
          if (notification.name) {
            description = `From ${notification.name}${notification.email ? ` (${notification.email})` : ''}: ${description}`;
          }
          break;
        default:
          title = 'Notification';
          iconType = 'info';
      }

      return {
        id: notification.id,
        type: notification.type,
        title,
        description,
        iconType,
        name: notification.name,
        email: notification.email,
        universityId: notification.university_id,
        consultantId: notification.consultant_id,
        studentId: notification.student_id,
        applicationId: notification.application_id,
        isRead: notification.is_read === 1,
        createdAt: notification.created_at,
        timestamp: notification.timestamp,
        timeAgo: getTimeAgo(notification.created_at)
      };
    });

    const unreadCount = notifications.filter(n => n.is_read === 0).length;

    return NextResponse.json({
      success: true,
      data: {
        notifications: formattedNotifications,
        unreadCount,
        totalCount: notifications.length
      }
    }, { status: 200 });

  } catch (err) {
    console.error('Notifications fetch error:', err);
    return NextResponse.json(
      { success: false, message: "Internal Server Error" },
      { status: 500 }
    );
  }
}

// Helper function to calculate time ago
function getTimeAgo(dateString: string | Date | null) {
  if (!dateString) return 'Recently';

  const date = new Date(dateString);
  const now = new Date();

  const seconds = Math.floor(
    (now.getTime() - date.getTime()) / 1000
  );

  let interval = seconds / 31536000;
  if (interval > 1) return Math.floor(interval) + ' years ago';

  interval = seconds / 2592000;
  if (interval > 1) return Math.floor(interval) + ' months ago';

  interval = seconds / 86400;
  if (interval > 1) return Math.floor(interval) + ' days ago';

  interval = seconds / 3600;
  if (interval > 1) return Math.floor(interval) + ' hours ago';

  interval = seconds / 60;
  if (interval > 1) return Math.floor(interval) + ' minutes ago';

  return 'Just now';
}


export async function DELETE(request: NextRequest) {
  try {
    const token = request.cookies.get("university-token")?.value || null;
    const decoded = await verifyAuthentication(token);

    if (decoded instanceof NextResponse || !decoded) {
      return NextResponse.json(
        { success: false, message: "Unauthorized" },
        { status: 401 }
      );
    }

    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');

    if (id) {
      // Delete specific notification
      await pool.query(
        `DELETE FROM notifications WHERE id = ? AND user_id = ?`,
        [id, decoded.id]
      );
    } else {
      // Delete all notifications for user
      await pool.query(
        `DELETE FROM notifications WHERE user_id = ?`,
        [decoded.id]
      );
    }

    return NextResponse.json({
      success: true,
      message: id ? 'Notification deleted' : 'All notifications cleared'
    }, { status: 200 });

  } catch (err) {
    console.error('Delete notification error:', err);
    return NextResponse.json(
      { success: false, message: "Internal Server Error" },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const token = request.cookies.get("university-token")?.value || null;
    const decoded = await verifyAuthentication(token);

    if (decoded instanceof NextResponse || !decoded) {
      return NextResponse.json(
        { success: false, message: "Unauthorized" },
        { status: 401 }
      );
    }

    const body = await request.json();
    const { markAllAsRead } = body;

    if (markAllAsRead) {
      await pool.query(
        `UPDATE notifications 
         SET is_read = 1 
         WHERE user_id = ?`,
        [decoded.id]
      );

      return NextResponse.json({
        success: true,
        message: 'All notifications marked as read'
      }, { status: 200 });
    }

    return NextResponse.json(
      { success: false, message: "Invalid request" },
      { status: 400 }
    );

  } catch (err) {
    console.error('Mark as read error:', err);
    return NextResponse.json(
      { success: false, message: "Internal Server Error" },
      { status: 500 }
    );
  }
}