import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

// Mark messages as read
export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const body = await req.json();
    const { conversationId, messageIds } = body;

    if (!conversationId && !messageIds) {
      return NextResponse.json(
        { error: 'Either conversationId or messageIds is required' },
        { status: 400 }
      );
    }

    // TODO: Add Message model to schema
    // Return mock success response for now
    return NextResponse.json({
      success: true,
      data: {
        updatedCount: messageIds ? messageIds.length : 5
      },
      message: 'Messages marked as read'
    });

  } catch (error) {
    console.error('Error marking messages as read:', error);
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to mark messages as read',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}

// Update user online status
export async function PUT(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const body = await req.json();
    const { status } = body; // 'online', 'busy', 'away', 'offline'

    if (!status || !['online', 'busy', 'away', 'offline'].includes(status)) {
      return NextResponse.json(
        { error: 'Invalid status. Must be one of: online, busy, away, offline' },
        { status: 400 }
      );
    }

    // TODO: Add onlineStatus field to User model
    // Return mock success response for now
    return NextResponse.json({
      success: true,
      data: {
        userId: session.user.email,
        status: status,
        lastSeen: new Date().toISOString()
      },
      message: 'Status updated successfully'
    });

  } catch (error) {
    console.error('Error updating user status:', error);
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to update status',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}

// Get unread message count
export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    // TODO: Add Message model to schema
    // Return mock data for now
    return NextResponse.json({
      success: true,
      data: {
        totalUnreadCount: 5,
        conversationUnreadCounts: {
          'conv-1': 2,
          'conv-2': 3
        }
      }
    });

  } catch (error) {
    console.error('Error getting unread message count:', error);
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to get unread count',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}