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 glPostingService = require('../services/glPostingService');

const generateMovementNumber = async (companyId) => {
  const today = new Date();
  const year = today.getFullYear();
  const prefix = `GR${year}`;
  
  const lastGR = await db.InventoryGoodsReceipt.findOne({
    where: {
      company_id: companyId,
      movement_number: { [Op.like]: `${prefix}%` }
    },
    order: [['movement_number', 'DESC']]
  });

  let sequence = 1;
  if (lastGR) {
    const lastSequence = parseInt(lastGR.movement_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] = [
      { movement_number: { [Op.like]: `%${search}%` } },
      { reference_number: { [Op.like]: `%${search}%` } }
    ];
  }

  const records = await db.InventoryGoodsReceipt.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: [['movement_date', 'DESC'], ['id', 'DESC']]
  });

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

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

  const gr = await db.InventoryGoodsReceipt.findByPk(id, {
    include: [
      { model: db.Company, as: 'company' },
      { model: db.Plant, as: 'plant' },
      { model: db.FiscalYear, as: 'fiscalYear' },
      {
        model: db.InventoryGoodsReceiptItem,
        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 (!gr) {
    return sendError(res, 404, 'Goods Receipt not found');
  }

  sendResponse(res, 200, true, 'Goods Receipt retrieved successfully', gr);
});

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

    grData.created_by = req.user.id;

    const gr = await db.InventoryGoodsReceipt.create(grData, { transaction });

    if (items && items.length > 0) {
      const itemsData = items.map((item, index) => ({
        movement_id: gr.id,
        line_number: item.item_number || index + 1,
        material_id: item.material_id,
        description: item.description,
        quantity: item.quantity,
        uom_id: item.uom_id,
        unit_price: item.unit_price || 0,
        total_amount: (item.quantity || 0) * (item.unit_price || 0),
        batch_number: item.batch_number || null,
        remarks: item.remarks || null
      }));

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

    await transaction.commit();

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

    sendResponse(res, 201, true, 'Goods Receipt created successfully', createdGR);
  } 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 gr = await db.InventoryGoodsReceipt.findByPk(id);
    
    if (!gr) {
      await transaction.rollback();
      return sendError(res, 404, 'Goods Receipt not found');
    }

    if (gr.status === 'POSTED') {
      await transaction.rollback();
      return sendError(res, 400, 'Cannot update posted Goods Receipt');
    }

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

    await gr.update(grData, { transaction });

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

      if (items.length > 0) {
        const itemsData = items.map((item, index) => ({
          movement_id: id,
          line_number: item.item_number || index + 1,
          material_id: item.material_id,
          description: item.description,
          quantity: item.quantity,
          uom_id: item.uom_id,
          unit_price: item.unit_price || 0,
          total_amount: (item.quantity || 0) * (item.unit_price || 0),
          batch_number: item.batch_number || null,
          remarks: item.remarks || null
        }));

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

    await transaction.commit();

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

    sendResponse(res, 200, true, 'Goods Receipt updated successfully', updatedGR);
  } catch (error) {
    await transaction.rollback();
    throw error;
  }
});

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

  const gr = await db.InventoryGoodsReceipt.findByPk(id);
  
  if (!gr) {
    return sendError(res, 404, 'Goods Receipt not found');
  }

  if (gr.status === 'POSTED') {
    return sendError(res, 400, 'Cannot delete posted Goods Receipt. Use status update to cancel.');
  }

  await db.InventoryGoodsReceiptItem.destroy({ where: { movement_id: id } });
  await gr.update({ status: 'CANCELLED', updated_by: req.user.id });

  sendResponse(res, 200, true, 'Goods Receipt cancelled successfully');
});

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

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

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

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

    await glPostingService.postInventoryMovementToGL(gr, 'GOODS_RECEIPT', req.user?.userId || req.user?.id);

    await transaction.commit();

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

    sendResponse(res, 200, true, 'Goods Receipt posted successfully', postedGR);
  } catch (error) {
    await transaction.rollback();
    throw error;
  }
});

