import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { Order } from '@/models/Order';
import { Student } from '@/models/Student';
import { Course } from '@/models/Course';
import { Lesson } from '@/models/Lesson';
import { requireAuth } from '@/lib/auth';

interface Params {
  params: { id: string };
}

// GET /api/orders/[id]
export async function GET(req: NextRequest, { params }: Params) {
  const auth = requireAuth(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const order = await Order.findById(params.id)
      .populate('student', 'name email phoneNumber')
      .populate('courseId', 'title level courseType regularPrice offerPrice')
      .populate('lessons', 'title price chapterNumber durationMinutes');

    if (!order) {
      return NextResponse.json({ success: false, error: 'Order not found' }, { status: 404 });
    }

    if (auth.user.role === 'student' && order.student._id.toString() !== auth.user.id) {
      return NextResponse.json({ success: false, error: 'Forbidden' }, { status: 403 });
    }

    return NextResponse.json({ success: true, order });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error fetching order' },
      { status: 500 }
    );
  }
}

// PUT /api/orders/[id] - Update gateway response / status
export async function PUT(req: NextRequest, { params }: Params) {
  const auth = requireAuth(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const body = await req.json();

    const order = await Order.findById(params.id);
    if (!order) {
      return NextResponse.json({ success: false, error: 'Order not found' }, { status: 404 });
    }

    if (auth.user.role === 'student' && order.student.toString() !== auth.user.id) {
      return NextResponse.json({ success: false, error: 'Forbidden' }, { status: 403 });
    }

    if (body.gatewayTransactionId) order.gatewayTransactionId = body.gatewayTransactionId;
    if (body.gatewayResponse) {
      order.gatewayResponse = { ...order.gatewayResponse, ...body.gatewayResponse };
    }
    if (body.status) {
      // Only admin can manually set status arbitrarily
      if (auth.user.role === 'admin' || auth.user.role === 'super_admin') {
        order.status = body.status;
      }
    }

    await order.save();

    return NextResponse.json({
      success: true,
      message: 'Order updated successfully',
      order,
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error updating order' },
      { status: 500 }
    );
  }
}
