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 EOD_CHANNEL = "1476344633406656785";

function formatEODBrief(data: any): string {
  return `🌙 END OF DAY - ${data.date || new Date().toISOString().split('T')[0]}

✅ COMPLETED TODAY
${(data.completed || []).map((c: string) => `- ${c}`).join('\n')}

📊 PROGRESS
${Object.entries(data.progress || {}).map(([k, v]) => `${k}: ${v}`).join('\n')}

🧠 COUNCIL
${Object.entries(data.council || {}).map(([k, v]) => `- ${k}: ${v}`).join('\n')}

🎯 TOMORROW
${(data.tomorrow || []).map((t: string) => `- ${t}`).join('\n')}`;
}

export async function GET() {
  const { data, error } = await supabase
    .from("eod_briefs")
    .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("eod_briefs")
      .insert([{
        date: body.date || new Date().toISOString().split('T')[0],
        completed: body.completed,
        progress: body.progress,
        council: body.council,
        tomorrow: body.tomorrow
      }]);
    
    if (error) {
      console.error("Supabase error:", error);
      return NextResponse.json({ error: error.message }, { status: 500 });
    }
    
    const discordMessage = formatEODBrief(body);
    await fetch(`https://discord.com/api/v10/channels/${EOD_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: "EOD brief saved and sent to Discord" });
  } catch (error) {
    return NextResponse.json({ error: "Failed" }, { status: 500 });
  }
}
