import { NextResponse } from 'next/server';
import OpenAI from 'openai';
import { query } from '@/lib/db';
import { getAdminSession } from '@/lib/auth';
import { logTokenUsage } from '@/lib/analytics/token-tracker';

const SYSTEM_PROMPT = `You are drafting customer support replies for Marich Wellness, an editorial wellness brand. An admin will review and edit your draft before sending.

Tone: warm, professional, calm. Acknowledge what the visitor wrote, then give a direct, helpful answer. No emoji. No corporate filler. No phrases like "I hope this finds you well."

Format:
- A short greeting using the visitor's first name only.
- One or two short paragraphs (3-5 sentences total). Keep it tight.
- If the question can't be fully answered without more info, ask for the specific detail you need.
- If the question is about something the team would normally handle (orders, account, technical), acknowledge it and say someone from the team will follow up.
- Sign off "Warmly," on its own line, then "The Marich Wellness Team" on the next line.

Output the reply body only. No subject line, no quoted message, no markdown headers, no "Hi <name>," scaffolding for the admin to fill in. Just the finished draft.`;

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 apiKey = process.env.OPENROUTER_API_KEY;
  const model = process.env.OPENROUTER_MODEL || 'meta-llama/llama-3.3-70b-instruct:free';
  if (!apiKey) {
    return NextResponse.json(
      { error: 'OPENROUTER_API_KEY is not configured. Add it to .env and restart the dev server.' },
      { status: 503 }
    );
  }

  const { id } = await params;

  // Get the conversation and the latest visitor message
  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];

  // Get the latest visitor message for context
  const msgRows = await query(
    `SELECT content FROM ConversationMessage
     WHERE conversation_id = ? AND sender_type = 'visitor'
     ORDER BY created_at DESC LIMIT 1`,
    [id]
  ) as any[];

  const latestVisitorMsg = msgRows.length > 0 ? msgRows[0].content : '';
  const conversationHistory = await query(
    `SELECT sender_type, content FROM ConversationMessage
     WHERE conversation_id = ?
     ORDER BY created_at ASC`,
    [id]
  ) as any[];

  const historyText = conversationHistory
    .map((m: any) => `[${m.sender_type === 'visitor' ? conv.visitor_name : 'Admin'}]: ${m.content}`)
    .join('\n');

  const userPrompt = `Visitor name: ${conv.visitor_name}\nVisitor email: ${conv.visitor_email}\n\nConversation history:\n"""\n${historyText}\n"""\n\nLatest visitor message:\n"""\n${latestVisitorMsg}\n"""\n\nDraft a reply.`;

  try {
    const client = new OpenAI({
      apiKey,
      baseURL: 'https://openrouter.ai/api/v1',
      defaultHeaders: {
        'HTTP-Referer': process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000',
        'X-Title': 'Marich Wellness Admin',
      },
    });

    const completion = await client.chat.completions.create({
      model,
      messages: [
        { role: 'system', content: SYSTEM_PROMPT },
        { role: 'user', content: userPrompt },
      ],
      temperature: 0.7,
      max_tokens: 600,
    });

    const draft = completion.choices?.[0]?.message?.content?.trim();
    if (!draft) {
      return NextResponse.json({ error: 'Model returned an empty draft.' }, { status: 502 });
    }

    // Track token usage for AI draft generation
    const tokensUsed = completion.usage?.total_tokens || 0;
    if (tokensUsed > 0) {
      await logTokenUsage('ai_draft_reply', tokensUsed, (session as any).email || 'unknown', 'openrouter');
    }

    return NextResponse.json({ draft, model });
  } catch (err: any) {
    console.error('[conversation-draft] OpenRouter error:', err?.message ?? err);
    const message = err?.status === 429
      ? 'Rate limited by OpenRouter. Try again in a moment.'
      : (err?.message as string) || 'Failed to generate draft.';
    return NextResponse.json({ error: message }, { status: 502 });
  }
}
