import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { ensureForumProfile } from '@/lib/forum/profile';

export async function POST(req: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json(
        { error: 'You must be signed in to post a reply.', auth_required: true },
        { status: 401 }
      );
    }

    const body = await req.json();
    const { thread_id, body: replyBody } = body;

    if (!thread_id || !replyBody) {
      return NextResponse.json({ error: 'thread_id and body are required' }, { status: 400 });
    }

    const { data: suspension } = await supabase
      .from('user_suspensions')
      .select('suspension_type, reason, expires_at')
      .eq('user_id', user.id)
      .eq('is_active', true)
      .or('expires_at.is.null,expires_at.gt.' + new Date().toISOString())
      .order('created_at', { ascending: false })
      .limit(1)
      .maybeSingle();

    if (suspension) {
      const isBanned = suspension.suspension_type === 'banned';
      const expiryText = suspension.expires_at
        ? ` until ${new Date(suspension.expires_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}`
        : '';
      return NextResponse.json(
        {
          error: isBanned
            ? `Your account has been permanently banned. Reason: ${suspension.reason}`
            : `Your account is suspended${expiryText}. Reason: ${suspension.reason}`,
          suspended: true,
          suspension_type: suspension.suspension_type,
        },
        { status: 403 }
      );
    }

    const forumProfile = await ensureForumProfile(user);

    const { data, error } = await supabase
      .from('forum_replies')
      .insert({
        thread_id,
        body: replyBody.trim(),
        author_id: user.id,
        author_name: forumProfile.display_name || forumProfile.username,
        is_ai_response: false,
      })
      .select()
      .single();

    if (error) throw error;

    // Auto-moderate with Claude (non-blocking on failure)
    try {
      const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000';
      const modRes = await fetch(`${baseUrl}/api/forum/auto-moderate`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          content_type: 'reply',
          body: replyBody.trim(),
        }),
      });

      if (modRes.ok) {
        const { moderation } = await modRes.json();
        if (moderation?.flagged) {
          await supabase
            .from('forum_replies')
            .update({
              is_flagged: true,
              flag_reason: `[AI] ${moderation.reason || 'Auto-flagged by moderation system'}`,
            })
            .eq('id', data.id);

          return NextResponse.json({
            reply: { ...data, is_flagged: true, flag_reason: `[AI] ${moderation.reason}` },
          }, { status: 201 });
        }
      }
    } catch {
      // AI moderation failure must not block reply creation
    }

    return NextResponse.json({ reply: data }, { status: 201 });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
