const db = require('../models');
const { sendResponse, sendError } = require('../utils/response');
const asyncHandler = require('../middlewares/asyncHandler');
const { getPagination, getPagingData } = require('../utils/pagination');
const { Op } = require('sequelize');

const generateAdjustmentNumber = async (companyId) => {
  const today = new Date();
  const year = today.getFullYear();
  const prefix = `SA${year}`;
  
  const lastSA = await db.InventoryStockAdjustment.findOne({
    where: {
      company_id: companyId,
      adjustment_number: { [Op.like]: `${prefix}%` }
    },
    order: [['adjustment_number', 'DESC']]
  });

  let sequence = 1;
  if (lastSA) {
    const lastSequence = parseInt(lastSA.adjustment_number.slice(-4)) || 0;
    sequence = lastSequence + 1;
  }

  return `${prefix}${sequence.toString().padStart(4, '0')}`;
};

exports.getAll = asyncHandler(async (req, res) => {
  const { page = 1, limit = 25, search, status, companyId, plantId, fiscalYearId } = req.query;
  const { limit: limitNum, offset } = getPagination(page, limit);

  const where = {};
  
  if (companyId) {
    where.company_id = companyId;
  } else if (req.user && !req.user.isSuperAdmin) {
    where.company_id = req.user.companyId;
  }

  if (plantId) {
    where.plant_id = plantId;
  }

  if (fiscalYearId) {
    where.fiscal_year_id = fiscalYearId;
  }

  if (status) {
    where.status = status;
  }

  if (search) {
    where[Op.or] = [
      { adjustment_number: { [Op.like]: `%${search}%` } }
    ];
  }

  const records = await db.InventoryStockAdjustment.findAndCountAll({
    where,
    include: [
      { model: db.Company, as: 'company', attributes: ['id', 'code', 'name'] },
      { model: db.Plant, as: 'plant', attributes: ['id', 'code', 'name'] }
    ],
    limit: limitNum,
    offset,
    order: [['adjustment_date', 'DESC'], ['id', 'DESC']]
  });

  const response = getPagingData(records, page, limitNum);
  sendResponse(res, 200, true, 'Stock Adjustments retrieved successfully', response);
});

exports.getById = asyncHandler(async (req, res) => {
  const { id } = req.params;

  const sa = await db.InventoryStockAdjustment.findByPk(id, {
    include: [
      { model: db.Company, as: 'company' },
      { model: db.Plant, as: 'plant' },
      { model: db.FiscalYear, as: 'fiscalYear' },
      {
        model: db.InventoryStockAdjustmentItem,
        as: 'items',
        include: [
          { model: db.Material, as: 'material' },
          { model: db.UOM, as: 'uom' }
        ],
        order: [['line_number', 'ASC']]
      },
      { model: db.User, as: 'postedByUser', attributes: ['id', 'first_name', 'last_name'] },
      { model: db.User, as: 'createdByUser', attributes: ['id', 'first_name', 'last_name'] }
    ]
  });

  if (!sa) {
    return sendError(res, 404, 'Stock Adjustment not found');
  }

  sendResponse(res, 200, true, 'Stock Adjustment retrieved successfully', sa);
});

exports.create = asyncHandler(async (req, res) => {
  const transaction = await db.sequelize.transaction();
  
  try {
    const { items, ...saData } = req.body;
    
    if (!saData.adjustment_number) {
      saData.adjustment_number = await generateAdjustmentNumber(saData.company_id || req.user.companyId);
    }

    saData.created_by = req.user.id;

    const sa = await db.InventoryStockAdjustment.create(saData, { transaction });

    if (items && items.length > 0) {
      const itemsData = await Promise.all(items.map(async (item, index) => {
        // Fetch system quantity from stock ledger (placeholder - TODO: implement stock ledger query)
        const systemQty = 0; // TODO: Get from stock ledger
        
        const physicalQty = parseFloat(item.physical_quantity) || 0;
        const adjustmentQty = physicalQty - systemQty;
        
        return {
          adjustment_id: sa.id,
          line_number: item.item_number || index + 1,
          material_id: item.material_id,
          description: item.description,
          system_quantity: systemQty,
          physical_quantity: physicalQty,
          adjustment_quantity: adjustmentQty,
          uom_id: item.uom_id,
          unit_price: item.unit_price || 0,
          adjustment_amount: adjustmentQty * (item.unit_price || 0),
          batch_number: item.batch_number || null,
          remarks: item.remarks || null
        };
      }));

      await db.InventoryStockAdjustmentItem.bulkCreate(itemsData, { transaction });
    }

    await transaction.commit();

    const createdSA = await db.InventoryStockAdjustment.findByPk(sa.id, {
      include: [
        { model: db.Company, as: 'company' },
        { model: db.Plant, as: 'plant' },
        {
          model: db.InventoryStockAdjustmentItem,
          as: 'items',
          include: [
            { model: db.Material, as: 'material' },
            { model: db.UOM, as: 'uom' }
          ]
        }
      ]
    });

    sendResponse(res, 201, true, 'Stock Adjustment created successfully', createdSA);
  } catch (error) {
    await transaction.rollback();
    throw error;
  }
});

exports.update = asyncHandler(async (req, res) => {
  const { id } = req.params;
  const transaction = await db.sequelize.transaction();
  
  try {
    const sa = await db.InventoryStockAdjustment.findByPk(id);
    
    if (!sa) {
      await transaction.rollback();
      return sendError(res, 404, 'Stock Adjustment not found');
    }

    if (sa.status === 'POSTED') {
      await transaction.rollback();
      return sendError(res, 400, 'Cannot update posted Stock Adjustment');
    }

    const { items, ...saData } = req.body;
    saData.updated_by = req.user.id;

    await sa.update(saData, { transaction });

    if (items) {
      await db.InventoryStockAdjustmentItem.destroy({ where: { adjustment_id: id }, transaction });

      if (items.length > 0) {
        const itemsData = await Promise.all(items.map(async (item, index) => {
          const systemQty = 0; // TODO: Get from stock ledger
          const physicalQty = parseFloat(item.physical_quantity) || 0;
          const adjustmentQty = physicalQty - systemQty;
          
          return {
            adjustment_id: id,
            line_number: item.item_number || index + 1,
            material_id: item.material_id,
            description: item.description,
            system_quantity: systemQty,
            physical_quantity: physicalQty,
            adjustment_quantity: adjustmentQty,
            uom_id: item.uom_id,
            unit_price: item.unit_price || 0,
            adjustment_amount: adjustmentQty * (item.unit_price || 0),
            batch_number: item.batch_number || null,
            remarks: item.remarks || null
          };
        }));

        await db.InventoryStockAdjustmentItem.bulkCreate(itemsData, { transaction });
      }
    }

    await transaction.commit();

    const updatedSA = await db.InventoryStockAdjustment.findByPk(id, {
      include: [
        { model: db.Company, as: 'company' },
        { model: db.Plant, as: 'plant' },
        {
          model: db.InventoryStockAdjustmentItem,
          as: 'items',
          include: [
            { model: db.Material, as: 'material' },
            { model: db.UOM, as: 'uom' }
          ]
        }
      ]
    });

    sendResponse(res, 200, true, 'Stock Adjustment updated successfully', updatedSA);
  } catch (error) {
    await transaction.rollback();
    throw error;
  }
});

exports.delete = asyncHandler(async (req, res) => {
  const { id } = req.params;

  const sa = await db.InventoryStockAdjustment.findByPk(id);
  
  if (!sa) {
    return sendError(res, 404, 'Stock Adjustment not found');
  }

  if (sa.status === 'POSTED') {
    return sendError(res, 400, 'Cannot delete posted Stock Adjustment. Use status update to cancel.');
  }

  await db.InventoryStockAdjustmentItem.destroy({ where: { adjustment_id: id } });
  await sa.update({ status: 'CANCELLED', updated_by: req.user.id });

  sendResponse(res, 200, true, 'Stock Adjustment cancelled successfully');
});

exports.post = asyncHandler(async (req, res) => {
  const { id } = req.params;
  const transaction = await db.sequelize.transaction();
  
  try {
    const sa = await db.InventoryStockAdjustment.findByPk(id, {
      include: [{ model: db.InventoryStockAdjustmentItem, as: 'items' }]
    });
    
    if (!sa) {
      await transaction.rollback();
      return sendError(res, 404, 'Stock Adjustment not found');
    }

    if (sa.status !== 'DRAFT') {
      await transaction.rollback();
      return sendError(res, 400, 'Only draft Stock Adjustment can be posted');
    }

    if (!sa.items || sa.items.length === 0) {
      await transaction.rollback();
      return sendError(res, 400, 'Cannot post Stock Adjustment without items');
    }

    await sa.update({
      status: 'POSTED',
      posted_at: new Date(),
      posted_by: req.user.id
    }, { transaction });

    // TODO: Update inventory stock ledger here
    // TODO: Create accounting entries here

    await transaction.commit();

    const postedSA = await db.InventoryStockAdjustment.findByPk(id, {
      include: [
        { model: db.Company, as: 'company' },
        { model: db.Plant, as: 'plant' },
        {
          model: db.InventoryStockAdjustmentItem,
          as: 'items',
          include: [
            { model: db.Material, as: 'material' },
            { model: db.UOM, as: 'uom' }
          ]
        }
      ]
    });

    sendResponse(res, 200, true, 'Stock Adjustment posted successfully', postedSA);
  } catch (error) {
    await transaction.rollback();
    throw error;
  }
});

