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

export async function GET(req: NextRequest) {
  try {
    const pool = getPool();
    const jalaliDate = req.nextUrl.searchParams.get("jalali_date");
    const dateValue = jalaliDate ? Number(jalaliDate) : null;

    let rows: any[];
    if (dateValue) {
      [rows] = await pool.query(
        "SELECT jalali_date, data FROM daily_checkbox_status WHERE jalali_date = ? ORDER BY jalali_date DESC",
        [dateValue]
      ) as unknown as [any[], any];
    } else {
      [rows] = await pool.query(
        "SELECT jalali_date, data FROM daily_checkbox_status ORDER BY jalali_date DESC"
      ) as unknown as [any[], any];
    }

    return NextResponse.json(rows);
  } catch (err) {
    console.error("Error fetching checkboxes:", err);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    const pool = getPool();
    const body = await req.json();
    const { date, data } = body;

    if (!date || !data) {
      return NextResponse.json(
        { error: "Missing date or data" },
        { status: 400 }
      );
    }

    await pool.query(
      "INSERT INTO daily_checkbox_status (jalali_date, data) VALUES (?, ?) ON DUPLICATE KEY UPDATE data = VALUES(data)",
      [date, JSON.stringify(data)]
    );

    return NextResponse.json({ success: true });
  } catch (err) {
    console.error("Error saving checkboxes:", err);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
