const BrandService = require('../services/brand.service');
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
const { createFileUploadDb } = require('../db/file_uploads.db');
const {
  insertBrandSchema,
  updateBrandSchema,
} = require('../validate/brand.schema');

class BrandController {
  // Get all brands
  static async getAll(req, res) {
    const queryParams = req.query;

    const results = await BrandService.getAllBrands(queryParams);
    const response = await setResponsePaging(queryParams, results, 'Brand found');

    res.status(response.statusCode).json(response);
  }

  // Get brand by ID
  static async getById(req, res) {
    const { id } = req.params;

    const results = await BrandService.getBrandById(id);

    // console.log('Brand response structure:', JSON.stringify(results, null, 2));

    const response = await setResponse(results, 'Brand found');

    res.status(response.statusCode).json(response);
  }

  // Create brand with nested error codes and solutions
  static async create(req, res) {
    const { error, value } = await checkValidate(insertBrandSchema, req);

    if (error) {
      return res.status(400).json(setResponse(error, 'Validation failed', 400));
    }

    value.created_by = req.user?.user_id || null;

    const results = await BrandService.createBrandWithFullData(value);
    const response = await setResponse(results, 'Brand created successfully');

    return res.status(response.statusCode).json(response);
  }

  // Update brand 
  static async update(req, res) {
    const { id } = req.params;

    const { error, value } = await checkValidate(updateBrandSchema, req);
    if (error) {
      return res.status(400).json(setResponse(error, 'Validation failed', 400));
    }

    try {
      if (req.file) {
        const file = req.file;
        const ext = require('path').extname(file.originalname).toLowerCase();
        const typeDoc = ext === ".pdf" ? "PDF" : "IMAGE";
        const folder = typeDoc === "PDF" ? "pdf" : "images";
        const pathDocument = `${folder}/${file.filename}`;

        // Insert to file_upload table
        const fileData = {
          file_upload_name: file.originalname,
          createdBy: req.user?.user_id || null,
        };
        await createFileUploadDb(fileData);
        
        if (value.error_code && Array.isArray(value.error_code)) {
          for (const errorCode of value.error_code) {
            if (errorCode.solution && Array.isArray(errorCode.solution)) {
              for (const solution of errorCode.solution) {
                if (solution.type_solution !== 'text' && (!solution.path_solution || solution.path_solution === '')) {
                  solution.path_solution = pathDocument;
                  solution.type_solution = typeDoc.toLowerCase();
                }
              }
            }
          }
        }
      }

      value.updated_by = req.user?.user_id || null;

      const results = await BrandService.updateBrandWithFullData(id, value);
      const response = await setResponse(results, 'Brand updated successfully');

      res.status(response.statusCode).json(response);

    } catch (error) {
      const response = setResponse([], error.message, error.statusCode || 500);
      res.status(response.statusCode).json(response);
    }
  }

  // Soft delete brand by ID
  static async delete(req, res) {
    const { id } = req.params;

    const results = await BrandService.deleteBrand(id, req.user.user_id);
    const response = await setResponse(results, 'Brand deleted successfully');

    res.status(response.statusCode).json(response);
  }
}

module.exports = BrandController;