from flask import Blueprint, render_template, session
from app.routes.auth import login_required
from app import mysql

main_bp = Blueprint('main', __name__)

@main_bp.route('/')
@login_required
def index():
    try:
        cursor = mysql.connection.cursor()
        cursor.execute("""
            SELECT DISTINCT c.id, c.title, c.created_at 
            FROM chats c
            LEFT JOIN messages m ON c.id = m.chat_id
            WHERE c.user_id = %s
            AND (m.id IS NOT NULL OR c.title != 'New Chat')
            ORDER BY c.updated_at DESC
        """, (session['user_id'],))
        chats = cursor.fetchall()
        
        return render_template('chat/chat.html', 
                             chats=chats, 
                             active_chat_id=session.get('active_chat_id'),
                             user_name=session.get('user_name'))
    except Exception as e:
        print(f"Error in index route: {str(e)}")
        return render_template('chat/index.html', 
                             chats=[], 
                             active_chat_id=None,
                             user_name=session.get('user_name'))