// Brand operations
const {
  getAllBrandsDb,
  getBrandByIdDb,
  getBrandByNameDb,
  createBrandDb,
  updateBrandDb,
  deleteBrandDb,
  checkBrandNameExistsDb,
} = require('../db/brand.db');

// Error code operations
const {
  getErrorCodesByBrandIdDb,
  createErrorCodeDb,
  updateErrorCodeDb,
  deleteErrorCodeDb,
} = require('../db/brand_code.db');

// Sparepart operations
const {
  getSparePartnsByErrorCodeIdDb,
  createSparePartDb,
  updateSparePartDb,
  deleteSparePartDb,
} = require('../db/brand_sparepart.db');

// Solution operations
const {
  getSolutionsByErrorCodeIdDb,
  createSolutionDb,
  updateSolutionDb,
  deleteSolutionDb,
} = require('../db/brand_code_solution.db');

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

class BrandService {

  static async getAllBrands(param) {
    try {
      const results = await getAllBrandsDb(param);
      return results;
    } catch (error) {
      throw new ErrorHandler(error.statusCode, error.message);
    }
  }

  static async getBrandById(id) {
    try {
      const brand = await getBrandByIdDb(id);
      if (!brand) throw new ErrorHandler(404, 'Brand not found');

      const errorCodes = await getErrorCodesByBrandIdDb(brand.brand_id);

      const errorCodesWithDetails = await Promise.all(
        errorCodes.map(async (errorCode) => {
          const solutions = await getSolutionsByErrorCodeIdDb(errorCode.error_code_id);

          const solutionsWithFile = await Promise.all(
            solutions.map(async (s) => {
              let fileData = null;

              if (s.path_solution && s.type_solution !== "text") {
                fileData = await getFileUploadByPathDb(s.path_solution);
              }

              return {
                ...s,
                file_upload_name: fileData?.file_upload_name || null,
                path_document: fileData?.path_document || null
              };
            })
          );

          const spareparts = await getSparePartnsByErrorCodeIdDb(errorCode.error_code_id);

          return {
            ...errorCode,
            solution: solutionsWithFile,
            sparepart: spareparts
          };
        })
      );

      return {
        ...brand,
        error_code: errorCodesWithDetails
      };

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

  static async createBrandWithFullData(data) {
    try {
      if (!data || typeof data !== "object") data = {};

      if (data.brand_name) {
        const exists = await checkBrandNameExistsDb(data.brand_name);
        if (exists) throw new ErrorHandler(400, "Brand name already exists");
      }

      if (!data.error_code || !Array.isArray(data.error_code)) {
        throw new ErrorHandler(400, "Brand must have at least 1 error code");
      }

      for (const ec of data.error_code) {
        if (!ec.solution || ec.solution.length === 0) {
          throw new ErrorHandler(400, `Error code ${ec.error_code} must have at least 1 solution`);
        }
      }

      const createdBrand = await createBrandDb({
        brand_name: data.brand_name,
        brand_type: data.brand_type,
        brand_manufacture: data.brand_manufacture,
        brand_model: data.brand_model,
        is_active: data.is_active,
        created_by: data.created_by
      });

      const brandId = createdBrand.brand_id;
      for (const ec of data.error_code) {
        const errorId = await createErrorCodeDb(brandId, {
          error_code: ec.error_code,
          error_code_name: ec.error_code_name,
          error_code_description: ec.error_code_description,
          error_code_color: ec.error_code_color,
          path_icon: ec.path_icon,
          is_active: ec.is_active,
          created_by: data.created_by
        });

        for (const s of ec.solution) {
          await createSolutionDb(errorId, {
            solution_name: s.solution_name,
            type_solution: s.type_solution,
            text_solution: s.text_solution || null,
            path_solution: s.path_solution || null,
            is_active: s.is_active,
            created_by: data.created_by
          });
        }

        if (Array.isArray(ec.sparepart)) {
          for (const sp of ec.sparepart) {
            await createSparePartDb(errorId, {
              sparepart_name: sp.sparepart_name,
              brand_sparepart_description: sp.brand_sparepart_description,
              path_foto: sp.path_foto || null,
              is_active: sp.is_active,
              created_by: data.created_by
            });
          }
        }

      }

      return await this.getBrandById(brandId);

    } catch (error) {
      throw new ErrorHandler(500, `Bulk insert failed: ${error.message}`);
    }
  }

  static async updateBrandWithFullData(id, data) {
    try {
      const existingBrand = await getBrandByIdDb(id);
      if (!existingBrand) throw new ErrorHandler(404, "Brand not found");

      await updateBrandDb(existingBrand.brand_name, {
        brand_name: data.brand_name,
        brand_type: data.brand_type,
        brand_manufacture: data.brand_manufacture,
        brand_model: data.brand_model,
        is_active: data.is_active,
        updated_by: data.updated_by
      });

      if (!data.error_code) return await this.getBrandById(id);

      const existingErrorCodes = await getErrorCodesByBrandIdDb(id);

      const incomingErrorCodes = data.error_code.map(ec => ec.error_code);

      for (const ec of data.error_code) {
        const existsEC = existingErrorCodes.find(e => e.error_code === ec.error_code);

        let errorId = null;

        if (existsEC) {
          await updateErrorCodeDb(existingBrand.brand_id, existsEC.error_code, {
            error_code_name: ec.error_code_name,
            error_code_description: ec.error_code_description,
            error_code_color: ec.error_code_color,
            path_icon: ec.path_icon,
            is_active: ec.is_active,
            updated_by: data.updated_by
          });
          errorId = existsEC.error_code_id;
        } else {
          errorId = await createErrorCodeDb(id, {
            error_code: ec.error_code,
            error_code_name: ec.error_code_name,
            error_code_description: ec.error_code_description,
            error_code_color: ec.error_code_color,
            path_icon: ec.path_icon,
            is_active: ec.is_active,
            created_by: data.updated_by
          });
        }

        const existingSolutions = await getSolutionsByErrorCodeIdDb(errorId);
        const incomingSolutionNames = ec.solution?.map(s => s.solution_name) || [];

        for (const s of ec.solution || []) {
          const existsSolution = existingSolutions.find(es => es.solution_name === s.solution_name);

          if (existsSolution) {
            await updateSolutionDb(existsSolution.brand_code_solution_id, {
              solution_name: s.solution_name,
              type_solution: s.type_solution,
              text_solution: s.text_solution || null,
              path_solution: s.path_solution || null,
              is_active: s.is_active,
              updated_by: data.updated_by
            });
          } else {
            await createSolutionDb(errorId, {
              solution_name: s.solution_name,
              type_solution: s.type_solution,
              text_solution: s.text_solution || null,
              path_solution: s.path_solution || null,
              is_active: s.is_active,
              created_by: data.updated_by
            });
          }
        }

        for (const es of existingSolutions) {
          if (!incomingSolutionNames.includes(es.solution_name)) {
            await deleteSolutionDb(es.brand_code_solution_id, data.updated_by);
          }
        }

        const existingSpareparts = await getSparePartnsByErrorCodeIdDb(errorId);
        const incomingSparepartNames = ec.sparepart?.map(sp => sp.sparepart_name) || [];

        for (const sp of ec.sparepart || []) {
          const existsSP = existingSpareparts.find(es => es.sparepart_name === sp.sparepart_name);

          if (existsSP) {
            await updateSparePartDb(existsSP.brand_sparepart_id, {
              sparepart_name: sp.sparepart_name,
              brand_sparepart_description: sp.brand_sparepart_description,
              path_foto: sp.path_foto || null,
              is_active: sp.is_active,
              updated_by: data.updated_by
            });
          } else {
            await createSparePartDb(errorId, {
              sparepart_name: sp.sparepart_name,
              brand_sparepart_description: sp.brand_sparepart_description,
              path_foto: sp.path_foto || null,
              is_active: sp.is_active,
              created_by: data.updated_by
            });
          }
        }

        for (const es of existingSpareparts) {
          if (!incomingSparepartNames.includes(es.sparepart_name)) {
            await deleteSparePartDb(es.brand_sparepart_id, data.updated_by);
          }
        }

      }

      for (const ec of existingErrorCodes) {
        if (!incomingErrorCodes.includes(ec.error_code)) {
          await deleteErrorCodeDb(id, ec.error_code, data.updated_by);
        }
      }

      return await this.getBrandById(id);

    } catch (error) {
      throw new ErrorHandler(500, `Update failed: ${error.message}`);
    }
  }

  static async deleteBrand(id, userId) {
    try {
      const exist = await getBrandByIdDb(id);
      if (!exist) throw new ErrorHandler(404, "Brand not found");

      return await deleteBrandDb(id, userId);

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

module.exports = BrandService;
