import { NextResponse } from 'next/server';
import { query, execute } from '@/lib/db';
import { getAdminSession } from '@/lib/auth';
import { sendContactReply } from '@/lib/email';

export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getAdminSession();
  if (!session) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const { id } = await params;
  const body = await request.json();
  const reply = (body?.reply ?? '').toString().trim();

  if (!reply) {
    return NextResponse.json({ error: 'Reply is empty.' }, { status: 400 });
  }
  if (reply.length > 10000) {
    return NextResponse.json({ error: 'Reply is too long (max 10000 characters).' }, { status: 400 });
  }

  // Get conversation details
  const convRows = await query(
    'SELECT id, visitor_name, visitor_email FROM Conversation WHERE id = ?',
    [id]
  ) as any[];

  if (!convRows || convRows.length === 0) {
    return NextResponse.json({ error: 'Conversation not found.' }, { status: 404 });
  }

  const conv = convRows[0];

  // Send email
  try {
    await sendContactReply({ to: conv.visitor_email, toName: conv.visitor_name, reply });
  } catch (err: any) {
    console.error('[conversation-send] SMTP error:', err?.message ?? err);
    return NextResponse.json(
      { error: err?.message || 'Failed to send email.' },
      { status: 502 }
    );
  }

  // Store admin reply as a message
  await execute(
    `INSERT INTO ConversationMessage (conversation_id, sender_type, content, status) VALUES (?, 'admin', ?, 'sent')`,
    [id, reply]
  );

  // Update conversation timestamp and status
  await execute(
    `UPDATE Conversation SET updated_at = CURRENT_TIMESTAMP, status = 'open' WHERE id = ?`,
    [id]
  );

  return NextResponse.json({ success: true, message: `Reply sent to ${conv.visitor_email}.` });
}
