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

// ✅ ADD Branch
export async function POST(req) {
  let connection;
  try {
    connection = await pool.getConnection();
    await connection.beginTransaction();

    const body = await req.json();
    const cleanedData = cleanData(body);

    const [result] = await connection.query(
      `INSERT INTO branches (location_type, name, address, city, state, pincode, phone, is_active) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        cleanedData.location_type,
        cleanedData.name,
        cleanedData.address,
        cleanedData.city,
        cleanedData.state || null,
        cleanedData.pincode || null,
        cleanedData.phone || null,
        cleanedData.is_active !== undefined ? cleanedData.is_active : 1,
      ]
    );

    await connection.commit();
    return Response.json(
      { message: "Branch added successfully", id: result.insertId },
      { status: 201 }
    );
  } catch (error) {
    if (connection) await connection.rollback();
    console.error("❌ Branch Add Error:", error);
    return Response.json(
      { error: "Failed to add branch", details: error.message },
      { status: 500 }
    );
  } finally {
    if (connection) connection.release();
  }
}

// ✅ GET Branches (with pagination + search)
export async function GET(req) {
  const { searchParams } = new URL(req.url);
  let pageIndex = parseInt(searchParams.get("pageIndex")) || 0;
  let pageSize = parseInt(searchParams.get("pageSize")) || 10;
  const filters = searchParams.get("filters");
  const activeOnly = searchParams.get("activeOnly") === "true";

  let name = "";
  let city = "";
  let location_type = "";

  if (filters) {
    try {
      const parsedFilters = globalJsonParse(filters);
      name = parsedFilters.name || "";
      city = parsedFilters.city || "";
      location_type = parsedFilters.location_type || "";
    } catch {
      return Response.json(
        { error: "Invalid filters format." },
        { status: 400 }
      );
    }
  }

  const offset = pageIndex * pageSize;

  let connection;
  try {
    connection = await pool.getConnection();

    let baseQuery = `
      SELECT 
        id, location_type, name, address, city, state, pincode, phone, is_active,
        DATE_FORMAT(created_at, '%Y-%m-%d') as created_at
      FROM branches
      WHERE 1 = 1
    `;
    let countQuery = `SELECT COUNT(*) as count FROM branches WHERE 1 = 1`;

    const queryParams = [];
    const countParams = [];

    if (activeOnly) {
      baseQuery += ` AND is_active = 1`;
      countQuery += ` AND is_active = 1`;
    }

    if (name) {
      baseQuery += ` AND name LIKE ?`;
      countQuery += ` AND name LIKE ?`;
      queryParams.push(`%${name}%`);
      countParams.push(`%${name}%`);
    }

    if (city) {
      baseQuery += ` AND city LIKE ?`;
      countQuery += ` AND city LIKE ?`;
      queryParams.push(`%${city}%`);
      countParams.push(`%${city}%`);
    }

    if (location_type) {
      baseQuery += ` AND location_type = ?`;
      countQuery += ` AND location_type = ?`;
      queryParams.push(location_type);
      countParams.push(location_type);
    }

    baseQuery += ` ORDER BY id ASC LIMIT ? OFFSET ?`;
    queryParams.push(pageSize, offset);

    const [rows] = await connection.query(baseQuery, queryParams);
    const [countResult] = await connection.query(countQuery, countParams);
    const rowCount = countResult[0]?.count || 0;

    return Response.json({ rows, rowCount }, { status: 200 });
  } catch (error) {
    console.error("❌ Branch Fetch Error:", error);
    return Response.json({ error: "Failed to fetch branches" }, { status: 500 });
  } finally {
    if (connection) connection.release();
  }
}

// ✅ DELETE Branch (Soft Delete)
export async function DELETE(req) {
  const { id } = await req.json();
  if (!id)
    return Response.json({ error: "Missing branch ID" }, { status: 400 });

  let connection;
  try {
    connection = await pool.getConnection();
    await connection.beginTransaction();

    await connection.query(`UPDATE branches SET is_active = 0 WHERE id = ?`, [
      id,
    ]);

    await connection.commit();
    return Response.json(
      { message: "Branch deleted successfully" },
      { status: 200 }
    );
  } catch (error) {
    if (connection) await connection.rollback();
    console.error("❌ Branch Delete Error:", error);
    return Response.json({ error: "Failed to delete branch" }, { status: 500 });
  } finally {
    if (connection) connection.release();
  }
}

// ✅ EDIT Branch
export async function PATCH(req) {
  let connection;
  try {
    connection = await pool.getConnection();
    await connection.beginTransaction();

    const body = await req.json();
    const cleanedData = cleanData(body);

    if (!cleanedData.id) {
      return Response.json({ error: "Missing branch ID" }, { status: 400 });
    }

    await connection.query(
      `UPDATE branches 
       SET location_type = ?, name = ?, address = ?, city = ?, state = ?, pincode = ?, phone = ?, is_active = ?
       WHERE id = ?`,
      [
        cleanedData.location_type,
        cleanedData.name,
        cleanedData.address,
        cleanedData.city,
        cleanedData.state || null,
        cleanedData.pincode || null,
        cleanedData.phone || null,
        cleanedData.is_active !== undefined ? cleanedData.is_active : 1,
        cleanedData.id,
      ]
    );

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