import { NextResponse } from 'next/server';
import dbConnect from '../../../../src/lib/mongodb';
import DashboardStats from '../../../../src/models/DashboardStats';

export async function GET() {
  try {
    await dbConnect();

    // Try to get existing dashboard stats, or create default if none exist
    let stats = await DashboardStats.findOne().sort({ createdAt: -1 });

    if (!stats) {
      // Create default stats if none exist
      stats = await DashboardStats.create({
        totalUsers: 1250,
        totalRevenue: 45000,
        activeSessions: 89,
        conversionRate: 3.2,
        recentActivity: [
          { id: '1', action: 'New user registered', timestamp: new Date('2024-01-15T10:30:00Z') },
          { id: '2', action: 'Payment processed', timestamp: new Date('2024-01-15T09:45:00Z') },
          { id: '3', action: 'Report generated', timestamp: new Date('2024-01-15T08:20:00Z') },
        ]
      });
    }

    return NextResponse.json({
      totalUsers: stats.totalUsers,
      totalRevenue: stats.totalRevenue,
      activeSessions: stats.activeSessions,
      conversionRate: stats.conversionRate,
      recentActivity: stats.recentActivity
    });
  } catch (error) {
    console.error('Error fetching dashboard data:', error);
    return NextResponse.json(
      { error: 'Failed to fetch dashboard data' },
      { status: 500 }
    );
  }
}

export async function POST(request: Request) {
  try {
    await dbConnect();

    const body = await request.json();

    const newStats = await DashboardStats.create({
      totalUsers: body.totalUsers || 0,
      totalRevenue: body.totalRevenue || 0,
      activeSessions: body.activeSessions || 0,
      conversionRate: body.conversionRate || 0,
      recentActivity: body.recentActivity || []
    });

    return NextResponse.json(newStats, { status: 201 });
  } catch (error) {
    console.error('Error creating dashboard stats:', error);
    return NextResponse.json(
      { error: 'Failed to create dashboard stats' },
      { status: 500 }
    );
  }
}
