import { NextResponse } from 'next/server';
import mongoose from 'mongoose';
import connectToDatabase from '@/lib/db';
import WebinarModel from '@/lib/models/webinar';
import WebinarRegistrationModel from '@/lib/models/webinar-registration';
import { sendEmail } from '@/lib/mail';

export const runtime = 'nodejs';

// Helper to find webinar by ID or slug
async function findWebinar(webinarId: string, Webinar: any) {
  if (mongoose.Types.ObjectId.isValid(webinarId)) {
    return await Webinar.findById(webinarId);
  }
  return await Webinar.findOne({ slug: webinarId });
}

export async function GET(
  request: Request,
  { params }: { params: Promise<{ webinarId: string }> }
) {
  try {
    const { webinarId } = await params;

    await connectToDatabase();
    const Webinar = mongoose.models.webinars || WebinarModel(mongoose);
    const WebinarRegistration =
      mongoose.models.webinar_registrations || WebinarRegistrationModel(mongoose);

    const webinar = await findWebinar(webinarId, Webinar);
    if (!webinar) {
      return NextResponse.json({ error: 'Webinar not found.' }, { status: 404 });
    }

    const registrations = await WebinarRegistration.find({ webinarId: webinar._id }).sort({
      createdAt: -1,
    });

    return NextResponse.json({ success: true, data: registrations }, { status: 200 });
  } catch (error) {
    console.error('Error fetching registrations:', error);
    return NextResponse.json(
      { error: 'Failed to fetch registrations. Please try again later.' },
      { status: 500 }
    );
  }
}

export async function POST(
  request: Request,
  { params }: { params: Promise<{ webinarId: string }> }
) {
  try {
    const { webinarId } = await params;
    const body = await request.json();
    const { name, email, phone, slotId } = body;

    if (!email || !email.trim()) {
      return NextResponse.json({ error: 'Email is required.' }, { status: 400 });
    }

    await connectToDatabase();
    const Webinar = mongoose.models.webinars || WebinarModel(mongoose);
    const WebinarRegistration =
      mongoose.models.webinar_registrations || WebinarRegistrationModel(mongoose);

    const webinar = await findWebinar(webinarId, Webinar);
    if (!webinar) {
      return NextResponse.json({ error: 'Webinar not found.' }, { status: 404 });
    }

    // Check if already registered
    const existingRegistration = await WebinarRegistration.findOne({
      webinarId: webinar._id,
      email: email.trim().toLowerCase(),
    });

    if (existingRegistration) {
      return NextResponse.json(
        { error: 'You are already registered for this webinar.' },
        { status: 400 }
      );
    }

    // Create registration
    const registration = new WebinarRegistration({
      webinarId: webinar._id,
      name: name?.trim() || '',
      email: email.trim().toLowerCase(),
      phone: phone?.trim() || '',
      slotId: slotId || '',
      status: 'Confirmed',
    });

    // Determine the timing for the email confirmation
    let webinarTimeLabel = `${webinar.date} at ${webinar.startTime} (IST)`;
    if (webinar.slotsEnabled && webinar.slots && slotId) {
      const selectedSlot = webinar.slots.find((s: any) => s.slotId === slotId);
      if (selectedSlot) {
        webinarTimeLabel = selectedSlot.label || `${selectedSlot.date} at ${selectedSlot.startTime}`;
      }
    }

    const meetLink = webinar.googleMeetLink || 'Will be shared before the event';

    // Try sending email
    const subject = `Confirmed: Registration for ${webinar.title}`;
    const text = `Hi ${name || 'there'},\n\nYour registration for "${webinar.title}" is confirmed!\n\nDate & Time: ${webinarTimeLabel}\nGoogle Meet Link: ${meetLink}\n\nWe look forward to seeing you there!\n\nBest regards,\nThe CodeframeAI Team`;
    
    const html = `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 5px;">
        <h2 style="color: #2d9895; margin-bottom: 20px;">Registration Confirmed!</h2>
        <p>Hi <strong>${name || 'there'}</strong>,</p>
        <p>You have successfully registered for the upcoming CodeframeAI webinar:</p>
        <div style="background-color: #f9f9f9; padding: 15px; border-left: 4px solid #2d9895; margin: 20px 0;">
          <h3 style="margin-top: 0; color: #333;">${webinar.title}</h3>
          <p style="margin: 5px 0;"><strong>Date & Time:</strong> ${webinarTimeLabel}</p>
          <p style="margin: 5px 0;"><strong>Google Meet Link:</strong> <a href="${meetLink}" target="_blank">${meetLink}</a></p>
        </div>
        <p>If you have any questions before the session, feel free to reply to this email.</p>
        <br/>
        <p>Best regards,</p>
        <p><strong>The CodeframeAI Team</strong></p>
      </div>
    `;

    // Send email (DO NOT block DB persistence)
    try {
      const emailResult = await sendEmail({
        to: email.trim().toLowerCase(),
        subject,
        text,
        html,
      });

      if (emailResult?.success) {
        registration.confirmationEmailSentAt = new Date();
      } else {
        console.error('[Registration] Email result not successful:', emailResult);
      }
    } catch (emailError) {
      console.error('[Registration] Email send failed (still saving registration):', emailError);
    }

    // DB diagnostics before save
    console.log('[Registration] Connection diagnostics:', {
      host: mongoose.connection?.host,
      name: mongoose.connection?.name,
      db: (mongoose.connection as any)?.db?.databaseName,
    });
    console.log('[Registration] Saving registration for webinar:', {
      webinarId: webinar._id?.toString?.() ?? webinar._id,
      email: email.trim().toLowerCase(),
    });

    await registration.save();

    // Post-save verification
    console.log('[Registration] Document saved. _id:', registration._id?.toString());
    console.log(
      '[Registration] Full saved doc:',
      JSON.stringify(registration.toObject(), null, 2)
    );

    const saved = await WebinarRegistration.findOne({
      _id: registration._id,
    });

    console.log('[Registration] Post-save verification (found doc?):', {
      found: !!saved,
      savedId: saved?._id?.toString?.(),
    });

    return NextResponse.json(
      {
        success: true,
        message: 'Registration successful! Confirmation email has been sent.',
        data: registration,
      },
      { status: 201 }
    );
  } catch (error: any) {
    console.error('Error in webinar registration API:', error);
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map((val: any) => val.message);
      return NextResponse.json(
        { error: `Validation Error: ${messages.join(', ')}` },
        { status: 400 }
      );
    }
    return NextResponse.json(
      { error: error.message || 'Failed to complete registration. Please try again later.' },
      { status: 500 }
    );
  }
}
