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

// Get file upload by path
const getFileUploadByPathDb = async (path) => {
  const queryText = `
    SELECT
      file_upload_id,
      file_upload_name,
      type_document,
      path_document,
      created_by,
      updated_by,
      deleted_by,
      created_at,
      updated_at,
      deleted_at
    FROM file_upload
    WHERE path_document = $1 AND deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [path]);
  return result.recordset[0];
};

// Create file upload
const createFileUploadDb = async (data) => {
  const store = {
    file_upload_name: data.file_upload_name,
  };

  // Add path_document if exists
  if (data.path_document) {
    store.path_document = data.path_document;
  }

  // Add type_document if exists
  if (data.type_document) {
    store.type_document = data.type_document;
  }

  if (data.createdBy) {
    store.created_by = data.createdBy;
  }

  console.log('Data to insert:', store);

  const queryText = `
    INSERT INTO file_upload (file_upload_name, path_document, type_document, created_by, created_at, updated_at)
    VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
    SELECT SCOPE_IDENTITY() as inserted_id;
  `;
  const values = [
    store.file_upload_name,
    store.path_document,
    store.type_document,
    store.created_by || null
  ];

  // console.log('Manual Query:', queryText);
  // console.log('Manual Values:', values);

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

// Soft delete file upload by path
const deleteFileUploadByPathDb = async (path, deletedBy = null) => {
  const store = {
    deleted_at: new Date(),
  };

  if (deletedBy) {
    store.deleted_by = deletedBy;
  }

  const whereData = {
    path_document: path,
  };

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

module.exports = {
  getFileUploadByPathDb,
  createFileUploadDb,
  deleteFileUploadByPathDb,
};