import { NextResponse } from 'next/server';
import OpenAI from 'openai';
import { query } from '@/lib/db';
import { getAdminSession } from '@/lib/auth';

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.`;

let schemaReady = false;
async function ensureSchema() {
  if (schemaReady) return;
  const { execute } = await import('@/lib/db');
  await execute(`ALTER TABLE ContactMessage ADD COLUMN reply_text TEXT`).catch(() => {});
  await execute(`ALTER TABLE ContactMessage ADD COLUMN replied_at DATETIME`).catch(() => {});
  schemaReady = true;
}

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

  await ensureSchema();
  const { id } = await params;

  const rows = (await query(
    'SELECT id, name, email, message 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];
  const userPrompt = `Visitor name: ${m.name}\nVisitor email: ${m.email}\n\nVisitor message:\n"""\n${m.message}\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 });
    }

    return NextResponse.json({ draft, model });
  } catch (err: any) {
    console.error('[draft-reply] OpenRouter error:', err?.message ?? err);
    const message = err?.status === 429
      ? 'Rate limited by OpenRouter. Try again in a moment.'
      : err?.message || 'Failed to generate draft.';
    return NextResponse.json({ error: message }, { status: 502 });
  }
}
