import pool from "@/lib/db";
import { handleFileUploads } from "@/lib/fileUpload";
import { cleanData } from "@/lib/utils";
import { removeImage } from "@/lib/removeImage";

export async function POST(req) {
  let connection;
  try {
    const formData = await req.formData();
    const body = Object.fromEntries(formData.entries());
    const cleanedData = cleanData(body);

    const uploadedFiles = await handleFileUploads(formData);

    connection = await pool.getConnection();
    await connection.beginTransaction();

    for (const [key, value] of Object.entries(cleanedData)) {
      // if (key !== "folder" && value !== null) {
      if (key !== "folder") {
        const stringValue =
          typeof value === "object" ? JSON.stringify(value) : value;

        const [existingSetting] = await connection.query(
          `SELECT id FROM settings WHERE settings_name = ?`,
          [key]
        );

        if (existingSetting.length > 0) {
          await connection.query(
            `UPDATE settings SET settings_value = ? WHERE settings_name = ?`,
            [stringValue, key]
          );
        } else {
          await connection.query(
            `INSERT INTO settings (settings_name, settings_value) VALUES (?, ?)`,
            [key, stringValue]
          );
        }
      }
    }

    for (const [key, filePath] of Object.entries(uploadedFiles)) {
      if (filePath) {
        const [existingFile] = await connection.query(
          `SELECT id, settings_value FROM settings WHERE settings_name = ?`,
          [key]
        );

        if (existingFile.length > 0) {
          // Remove old image if it exists
          const oldImagePath = existingFile[0].settings_value;
          if (oldImagePath) {
            removeImage(oldImagePath);
          }

          await connection.query(
            `UPDATE settings SET settings_value = ? WHERE settings_name = ?`,
            [filePath, key]
          );
        } else {
          await connection.query(
            `INSERT INTO settings (settings_name, settings_value) VALUES (?, ?)`,
            [key, filePath]
          );
        }
      }
    }

    await connection.commit();
    return Response.json(
      { message: "Settings updated successfully" },
      { status: 200 }
    );
  } catch (error) {
    if (connection) await connection.rollback();
    console.error("❌ API Error:", error);
    return Response.json(
      { error: "Failed to update settings", details: error.message },
      { status: 500 }
    );
  } finally {
    if (connection) connection.release();
  }
}

export async function GET() {
  let connection;
  try {
    connection = await pool.getConnection();
    await connection.beginTransaction();

    const [rows] = await connection.query(
      `SELECT id, settings_name, settings_value FROM settings`
    );

    const parsedRows = rows.map((row) => {
      let value = row.settings_value;
      try {
        const parsed = globalJsonParse(row.settings_value);
        if (typeof parsed === "object") value = parsed;
      } catch (_) {}
      return {
        id: row.id,
        settings_name: row.settings_name,
        settings_value: value,
      };
    });

    await connection.commit();
    return Response.json({ rows: parsedRows }, { status: 200 });
  } catch (error) {
    if (connection) await connection.rollback();
    return Response.json(
      { error: "Failed to fetch settings" },
      { status: 500 }
    );
  } finally {
    if (connection) connection.release();
  }
}
