import { NextRequest, NextResponse } from "next/server";
import { supabase } from "@/lib/supabase";

const DISCORD_BOT_TOKEN = process.env.DISCORD_BOT_TOKEN || "MTQ3MTk4OTUzNjE1MzQwMzU5Nw.Ghtj4n.g-tl-Ijhfn9cg6zUCUIVd94EdwL32KmlVgRoSc";
const GENERAL_CHANNEL = "1476261655955378401";

function formatAmunBrief(data: any): string {
  return `👑 AMUN QA REPORT - ${data.date || new Date().toISOString().split('T')[0]}

🔍 TESTS RUN
${(data.tests || []).map((t: string) => `- ${t}`).join('\n')}

🐛 BUGS FOUND
${(data.bugs || []).map((b: string) => `- ${b}`).join('\n')}

📊 QUALITY SCORE: ${data.quality || 'N/A'}

💡 RECOMMENDATIONS
${(data.recommendations || []).map((r: string) => `- ${r}`).join('\n')}`;
}

export async function GET() {
  const { data, error } = await supabase
    .from("amun_sessions")
    .select("*")
    .order("created_at", { ascending: false })
    .limit(20);
  
  if (error) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
  return NextResponse.json(data || []);
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    const { data: insertData, error } = await supabase
      .from("amun_sessions")
      .insert([{
        date: body.date || new Date().toISOString().split('T')[0],
        tests: body.tests,
        bugs: body.bugs,
        quality: body.quality,
        recommendations: body.recommendations
      }]);
    
    if (error) {
      console.error("Supabase error:", error);
      return NextResponse.json({ error: error.message }, { status: 500 });
    }
    
    const discordMessage = formatAmunBrief(body);
    await fetch(`https://discord.com/api/v10/channels/${GENERAL_CHANNEL}/messages`, {
      method: "POST",
      headers: {
        "Authorization": `Bot ${DISCORD_BOT_TOKEN}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ content: discordMessage }),
    });
    
    return NextResponse.json({ success: true, message: "Amun brief saved and sent to Discord" });
  } catch (error) {
    return NextResponse.json({ error: "Failed" }, { status: 500 });
  }
}
