using OfficeOpenXml;
using Domain.Dtos.Stock;
using Transversal.Interfaces;

namespace Transversal.Services
{
    public class XLSXImportBase : IXLSXImportBase
    {
        public List<ProductImportPreviewDto> ReadProductImport(byte[] fileBytes)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            var result = new List<ProductImportPreviewDto>();

            using var stream = new MemoryStream(fileBytes);
            using var package = new ExcelPackage(stream);

            var worksheet = package.Workbook.Worksheets.FirstOrDefault();
            if (worksheet == null)
                throw new Exception("El archivo no contiene hojas válidas.");

            int row = 2;
            while (true)
            {
                var factoryCode = worksheet.Cells[row, 1].Text?.Trim();
                if (string.IsNullOrWhiteSpace(factoryCode)) break; // fin del archivo

                var item = new ProductImportPreviewDto
                {
                    FactoryCode = factoryCode,
                    Name = worksheet.Cells[row, 2].Text?.Trim(),
                    Description = worksheet.Cells[row, 3].Text?.Trim(),
                    ProductType = int.TryParse(worksheet.Cells[row, 4].Text, out var pt) ? pt : 0,
                    TraceabilityType = int.TryParse(worksheet.Cells[row, 5].Text, out var tt) ? tt : 0,
                    DivisionCode = worksheet.Cells[row, 6].Text?.Trim(),
                    UnitCode = worksheet.Cells[row, 7].Text?.Trim(),
                    PlusProcess = worksheet.Cells[row, 8].Text.Trim().ToLower() == "sí" || worksheet.Cells[row, 8].Text.Trim().ToLower() == "si",
                    ExternalCode = worksheet.Cells[row, 9].Text?.Trim(),
                };

                result.Add(item);
                row++;
            }

            return result;
        }
    }
}
