const {
  getAllNotificationDb,
  getNotificationByIdDb,
  insertNotificationDb,
  updateNotificationDb,
  deleteNotificationDb,
} = require('../db/notification.db');

const {
  getErrorCodeByIdDb,
} = require('../db/brand_code.db');

const {
  getSolutionsByErrorCodeIdDb,
} = require('../db/brand_code_solution.db');

const {
  getSparePartnsByErrorCodeIdDb,
} = require('../db/brand_sparepart.db');

const {
  getAllNotificationErrorLogDb,
} = require('../db/notification_error_log.db');

const { getFileUploadByPathDb } = require('../db/file_uploads.db');

const { ErrorHandler } = require('../helpers/error');

class NotificationService {
  // Get all Notifications
  static async getAllNotification(param) {
    try {
      const results = await getAllNotificationDb(param);

      results.data.map(element => {
      });

      return results;
    } catch (error) {
      throw new ErrorHandler(error.statusCode, error.message);
    }
  }

  // Get notification by ID
  static async getNotificationById(id) {
    try {
      const notification = await getNotificationByIdDb(id);

      if (!notification || (Array.isArray(notification) && notification.length < 1)) {
        throw new ErrorHandler(404, 'Notification not found');
      }

      // Get error code details if error_code_id exists
      if (notification.error_code_id) {
        const errorCode = await getErrorCodeByIdDb(notification.error_code_id);

        if (errorCode) {
          // Get solutions for this error code
          const solutions = (await getSolutionsByErrorCodeIdDb(errorCode.error_code_id)) || [];

          const solutionsWithDetails = await Promise.all(
            solutions.map(async (solution) => {
              let fileData = null;
              if (solution.path_solution && solution.type_solution && solution.type_solution !== 'text') {
                try {
                  fileData = await getFileUploadByPathDb(solution.path_solution);
                } catch (e) {
                  fileData = null;
                }
              }
              return {
                ...solution,
                file_upload_name: fileData?.file_upload_name || null,
                path_document: fileData?.path_document || null
              };
            })
          );

          // Get spareparts for this error code
          const spareparts = (await getSparePartnsByErrorCodeIdDb(errorCode.error_code_id)) || [];

          notification.error_code = {
            ...errorCode,
            solution: solutionsWithDetails,
            sparepart: spareparts
          };
        }
      }

      // Get activity logs for this notification
      const activityLogs = (await getAllNotificationErrorLogDb()) || [];
      const notificationLogs = activityLogs.filter(log => log.notification_error_id === parseInt(id));

      notification.activity_logs = notificationLogs;

      return notification;
    } catch (error) {
      throw new ErrorHandler(error.statusCode, error.message);
    }
  }

  static async createNotification(data) {
    try {
      if (!data || typeof data !== 'object') data = {};

      const result = await insertNotificationDb(data);
      return result;
    } catch (error) {
      throw new ErrorHandler(error.statusCode, error.message);
    }
  }

  static async updateNotification(id, data) {
    try {
      if (!data || typeof data !== 'object') data = {};

      const dataExist = await getNotificationByIdDb(id);

      if (!dataExist || (Array.isArray(dataExist) && dataExist.length < 1)) {
        throw new ErrorHandler(404, 'Notification not found');
      }

      const result = await updateNotificationDb(id, data);
      return result;
    } catch (error) {
      throw new ErrorHandler(error.statusCode, error.message);
    }
  }

  static async deleteNotification(id, userId) {
    try {
      const dataExist = await getNotificationByIdDb(id);

      if (!dataExist || (Array.isArray(dataExist) && dataExist.length < 1)) {
        throw new ErrorHandler(404, 'Notification not found');
      }

      const result = await deleteNotificationDb(id, userId);
      return result;
    } catch (error) {
      throw new ErrorHandler(error.statusCode, error.message);
    }
  }
}

module.exports = NotificationService;
