const PilonInvoices = require("../../models/PilonInvoices");
const PilonInvoicesFiles = require("../../models/PilonInvoicesFiles");
const { Op } = require("sequelize");
const sequelize = require("../../connection/db");

exports.getAllPilonInvoices = async (req, res, next) => {
  const {
    pageNumber = 1,
    pageSize = 20,
    filterField = "",
    filterValue = "",
  } = req.query;

  try {
    const offset = (pageNumber - 1) * pageSize;
    const limit = parseInt(pageSize);

    const validFields = Object.keys(PilonInvoices.rawAttributes);

    if (filterField && !validFields.includes(filterField)) {
      return res.status(400).json({
        success: false,
        message: `Invalid filter field: ${filterField}`,
      });
    }

    const whereCondition =
      filterField && filterValue
        ? { [filterField]: { [Op.like]: `%${filterValue}%` } }
        : {};

    const { rows, count } = await PilonInvoices.findAndCountAll({
      where: whereCondition,
      include: [
        {
          model: PilonInvoicesFiles,
          as: "files",
        },
      ],
      limit,
      offset,
      order: [["createdAt", "DESC"]],
    });

    res.status(200).json({
      success: true,
      data: rows,
      pagination: {
        totalRecords: count,
        currentPage: parseInt(pageNumber),
        totalPages: Math.ceil(count / pageSize),
      },
    });
  } catch (err) {
    next(err);
  }
};

const pilonInvoiceResponseMapper = (invoice) => ({
  id: invoice.id,
  amount: invoice.amount,
  invoiceNo: invoice.invoice_no,
  clienCode: invoice.clien_code,
  supplierCode: invoice.supplier_code,
  status: invoice.status,
  statusDescription: invoice.status_description,
  discountPercentage: invoice.discount_percentage,
  discountAmount: invoice.discount_amount,
  newPayee: invoice.new_payee,
  fundRequestDate: invoice.fund_request_date?.toISOString() || null,
  earlyPayDate: invoice.early_payment_date?.toISOString() || null,
  buyerpaymentDate: invoice.buyer_payment_date?.toISOString() || null,
  createdAt: invoice.createdAt?.toISOString(),
  updatedAt: invoice.updatedAt?.toISOString(),
});

exports.pilonPostReturnFile = async (req, res, next) => {
  const {
    amount = 0,
    invoiceNo,
    clienCode,
    supplierCode,
    status,
    statusDescription,
    discountPercentage,
    discountAmount = 0,
    newPayee,
    fundRequestDate,
    earlyPayDate,
    buyerpaymentDate,
  } = req.body;

  if (!invoiceNo || !clienCode || !supplierCode) {
    return res.status(400).json({
      success: false,
      message: "Missing required fields: invoiceNo, clienCode, or supplierCode",
    });
  }

  const transaction = await sequelize.transaction();

  try {
    const pilonInvoice = await PilonInvoices.create(
      {
        amount,
        invoice_no: invoiceNo,
        clien_code: clienCode,
        supplier_code: supplierCode,
        status,
        status_description: statusDescription,
        discount_percentage: discountPercentage,
        discount_amount: discountAmount,
        new_payee: newPayee,
        fund_request_date: fundRequestDate ? new Date(fundRequestDate) : null,
        early_payment_date: earlyPayDate ? new Date(earlyPayDate) : null,
        buyer_payment_date: buyerpaymentDate
          ? new Date(buyerpaymentDate)
          : null,
      },
      { transaction }
    );

    await transaction.commit();

    res.status(201).json({
      success: true,
      message: "Pilon invoice created successfully.",
      data: pilonInvoiceResponseMapper(pilonInvoice),
    });
  } catch (err) {
    await transaction.rollback();
    console.error("Error creating Pilon invoice:", err);
    next(err);
  }
};
