import { NextRequest, NextResponse } from "next/server";
import { db } from "@/db";
import { morningBriefs, eodBriefs, amunSessions } from "@/db/schema";
import { desc } from "drizzle-orm";

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const days = parseInt(searchParams.get("days") || "30");

    const [mornings, eods, amuns] = await Promise.all([
      db.select().from(morningBriefs).orderBy(desc(morningBriefs.date)).limit(days),
      db.select().from(eodBriefs).orderBy(desc(eodBriefs.date)).limit(days),
      db.select().from(amunSessions).orderBy(desc(amunSessions.date)).limit(days),
    ]);

    // Parse JSON fields for dashboard consumption
    const parsedMornings = mornings.map((b) => ({
      ...b,
      marketData: safeJson(b.marketData, {}),
      aiNewsHeadlines: safeJson(b.aiNewsHeadlines, []),
      skillsToLearn: safeJson(b.skillsToLearn, []),
      sitementeStatus: safeJson(b.sitementeStatus, {}),
      warmLeads: safeJson(b.warmLeads, []),
      dayPriorities: safeJson(b.dayPriorities, []),
      skippedTasks: safeJson(b.skippedTasks, []),
    }));

    const parsedEods = eods.map((b) => ({
      ...b,
      marketUpdate: safeJson(b.marketUpdate, {}),
      completedTasks: safeJson(b.completedTasks, []),
      tomorrowPriorities: safeJson(b.tomorrowPriorities, []),
      councilFeedback: safeJson(b.councilFeedback, {}),
      projectProgress: safeJson(b.projectProgress, []),
    }));

    const parsedAmuns = amuns.map((s) => ({
      ...s,
      testsRun: safeJson(s.testsRun, []),
      bugsFound: safeJson(s.bugsFound, []),
      recommendations: safeJson(s.recommendations, []),
    }));

    return NextResponse.json({
      mornings: parsedMornings,
      eods: parsedEods,
      amuns: parsedAmuns,
    });
  } catch (error) {
    console.error("GET /api/dashboard error:", error);
    return NextResponse.json({ error: "Failed to fetch dashboard data" }, { status: 500 });
  }
}

function safeJson<T>(str: string, fallback: T): T {
  try {
    return JSON.parse(str) as T;
  } catch {
    return fallback;
  }
}
