const pool = require("../config");

// Get all brands
const getAllBrandsDb = async (searchParams = {}) => {
  let queryParams = [];

  // Pagination
  if (searchParams.limit) {
    const page = Number(searchParams.page ?? 1) - 1;
    queryParams = [Number(searchParams.limit ?? 10), page];
  }

  // Search
  const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
    ["a.brand_name", "a.brand_type", "a.brand_manufacture", "a.brand_model", "a.brand_code"],
    searchParams.criteria,
    queryParams
  );

  queryParams = whereParamOr ? whereParamOr : queryParams;

  // Filter
  const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
    [
      { column: "a.brand_type", param: searchParams.type, type: "string" },
      { column: "a.brand_manufacture", param: searchParams.manufacture, type: "string" },
      { column: "a.brand_model", param: searchParams.model, type: "string" },
      { column: "a.is_active", param: searchParams.status, type: "string" },
    ],
    queryParams
  );

  queryParams = whereParamAnd ? whereParamAnd : queryParams;

  const queryText = `
    SELECT
      COUNT(*) OVER() AS total_data,
      a.*
    FROM m_brands a
    WHERE a.deleted_at IS NULL
      ${whereConditions.length > 0 ? `AND ${whereConditions.join(' AND ')}` : ''}
      ${whereOrConditions ? whereOrConditions : ''}
    ORDER BY a.brand_id ASC
    ${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
  `;

  const result = await pool.query(queryText, queryParams);
  const total =
    result?.recordset.length > 0
      ? parseInt(result.recordset[0].total_data, 10)
      : 0;

  return { data: result.recordset, total };
};

// Get brand by name (path-based)
const getBrandByNameDb = async (brandName) => {
  const queryText = `
    SELECT
      a.*
    FROM m_brands a
    WHERE a.brand_name = $1 AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [brandName]);
  return result.recordset[0];
};

// Get brand by ID (for internal use)
const getBrandByIdDb = async (id) => {
  const queryText = `
    SELECT
      a.*
    FROM m_brands a
    WHERE a.brand_id = $1 AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [id]);
  return result.recordset[0];
};

// Create brand
const createBrandDb = async (data) => {
  const newCode = await pool.generateKode("BRD", "m_brands", "brand_code");

  const store = {
    ...data,
    brand_code: newCode,
  };

  const { query: queryText, values } = pool.buildDynamicInsert("m_brands", store);
  const result = await pool.query(queryText, values);
  const insertedId = result.recordset[0]?.inserted_id;
  return insertedId ? await getBrandByIdDb(insertedId) : null;
};

// Update brand by name
const updateBrandDb = async (brandName, data) => {
  const store = { ...data };
  const whereData = { brand_name: brandName };

  const { query: queryText, values } = pool.buildDynamicUpdate("m_brands", store, whereData);
  await pool.query(`${queryText} AND deleted_at IS NULL`, values);
  return getBrandByNameDb(brandName);
};

// Soft delete brand 
const deleteBrandDb = async (id, deletedBy) => {
  const queryText = `
    UPDATE m_brands
    SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
    WHERE brand_id = $2 AND deleted_at IS NULL
  `;
  await pool.query(queryText, [deletedBy, id]);
  return true;
};

// Check if brand name exists (for validation)
const checkBrandNameExistsDb = async (brandName, excludeId = null) => {
  let queryText = `
    SELECT brand_id
    FROM m_brands
    WHERE brand_name = $1 AND deleted_at IS NULL
  `;
  let values = [brandName];

  if (excludeId) {
    queryText += ` AND brand_id != $2`;
    values.push(excludeId);
  }

  const result = await pool.query(queryText, values);
  return result.recordset.length > 0;
};


module.exports = {
  getAllBrandsDb,
  getBrandByNameDb,
  getBrandByIdDb,
  createBrandDb,
  updateBrandDb,
  deleteBrandDb,
  checkBrandNameExistsDb,
};