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 });
  }

  await execute(`ALTER TABLE ContactMessage ADD COLUMN reply_text TEXT`).catch(() => {});
  await execute(`ALTER TABLE ContactMessage ADD COLUMN replied_at DATETIME`).catch(() => {});

  const rows = (await query(
    'SELECT id, name, email FROM ContactMessage WHERE id = ?',
    [id]
  )) as any[];

  if (!rows || rows.length === 0) {
    return NextResponse.json({ error: 'Message not found.' }, { status: 404 });
  }

  const m = rows[0];

  try {
    await sendContactReply({ to: m.email, toName: m.name, reply });
  } catch (err: any) {
    console.error('[send-reply] SMTP error:', err?.message ?? err);
    return NextResponse.json(
      { error: err?.message || 'Failed to send email.' },
      { status: 502 }
    );
  }

  await execute(
    `UPDATE ContactMessage SET status = 'replied', reply_text = ?, replied_at = CURRENT_TIMESTAMP WHERE id = ?`,
    [reply, id]
  );

  return NextResponse.json({ success: true, message: `Reply sent to ${m.email}.` });
}
