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 MORNING_CHANNEL = "1476344610493042698";

function formatMorningBrief(data: any): string {
  return `☀️ MORNING BRIEF - ${data.date || new Date().toISOString().split('T')[0]}

🌤️ WEATHER
${data.weather || 'N/A'}

📊 MARKET
BTC: $${data.market?.BTC || 'N/A'} (${data.market?.btcChange || '0%'})
ETH: $${data.market?.ETH || 'N/A'} (${data.market?.ethChange || '0%'})
SOL: $${data.market?.SOL || 'N/A'} (${data.market?.solChange || '0%'})

🎯 PRIORITIES
${(data.priorities || []).map((p: string, i: number) => `${i + 1}. ${p}`).join('\n')}

💰 GOAL: ${data.goal || 'N/A'}

🔥 HOT LEADS
${(data.leads || []).map((l: string) => `- ${l}`).join('\n')}`;
}

export async function GET() {
  const { data, error } = await supabase
    .from("morning_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();
    
    // Save to Supabase
    const { data, error } = await supabase
      .from("morning_briefs")
      .insert([{
        date: body.date || new Date().toISOString().split('T')[0],
        weather: body.weather,
        market: body.market,
        priorities: body.priorities,
        goal: body.goal,
        leads: body.leads
      }]);
    
    if (error) {
      console.error("Supabase error:", error);
      return NextResponse.json({ error: error.message }, { status: 500 });
    }
    
    // Send to Discord
    const discordMessage = formatMorningBrief(body);
    await fetch(`https://discord.com/api/v10/channels/${MORNING_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: "Morning brief saved and sent to Discord" });
  } catch (error) {
    console.error("Error:", error);
    return NextResponse.json({ error: "Failed to save brief" }, { status: 500 });
  }
}
