import { NextResponse } from "next/server";
import { db } from "@/lib/db";

export async function GET() {
  try {
    const [goals]: any = await db.query(`SELECT * FROM goals ORDER BY created_at DESC`);
    const goalsWithProgress = await Promise.all(goals.map(async (goal: any) => {
      let mConditions = ["m.created_at BETWEEN ? AND ?"];
      let mParams: any[] = [goal.start_date, goal.end_date];
      if (goal.section_number) { mConditions.push("m.section_number = ?"); mParams.push(goal.section_number); }
      if (goal.neighborhood) { mConditions.push("m.neighborhood = ?"); mParams.push(goal.neighborhood); }
      if (goal.user_id) { mConditions.push("m.leader_id = ?"); mParams.push(goal.user_id); }
      const [res]: any = await db.query(`SELECT COUNT(*) as current FROM militants m WHERE ${mConditions.join(" AND ")}`, mParams);
      const current = res[0].current || 0;
      const percent = goal.target_count > 0 ? Math.round((current / goal.target_count) * 100) : 0;
      return { ...goal, current, percent: percent > 100 ? 100 : percent };
    }));
    return NextResponse.json(goalsWithProgress);
  } catch (error) { return NextResponse.json({ error: "Error" }, { status: 500 }); }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { title, target_count, start_date, end_date, user_id, neighborhood, section_number } = body;
    await db.query(`INSERT INTO goals (title, target_count, start_date, end_date, user_id, neighborhood, section_number) VALUES (?, ?, ?, ?, ?, ?, ?)`, 
    [title, target_count, start_date, end_date, user_id || null, neighborhood || null, section_number || null]);
    return NextResponse.json({ message: "OK" });
  } catch (error) { return NextResponse.json({ error: "Error" }, { status: 500 }); }
}

export async function DELETE(request: Request) {
  const { searchParams } = new URL(request.url);
  const id = searchParams.get("id");
  await db.query(`DELETE FROM goals WHERE id = ?`, [id]);
  return NextResponse.json({ message: "OK" });
}