const Rpaf = require("../../models/Rpaf");
const errorHandler = require("../../util/errorHandler");

exports.getDraftRpaf = (req, res, next) => {
  const { customerId } = req.params;

  Rpaf.findOne({
    where: {
      customer_id: customerId,
      status: "Draft",
    },
  })
    .then((credit) => {
      if (!credit) {
        return res.status(404).json({ success: false, message: "Credit application not found." });
      }

      const baseURL = "https://api.buildhubware.com/public/rpaf-build-credit-application-upload/";

      const creditApplication = {
        id: credit.id,
        customerId: credit.customer_id,
        status: credit.status,
        creditLimit: credit.credit_limit,
        companyName: credit.company_name,
        contactPerson: credit.contact_person,
        companyEmail: credit.company_email,
        phoneNo: credit.phone,
        altPhoneNo: credit.addtl_phone,
        landline: credit.landline,
        area: credit.area,
        address: credit.address,
        additionalInfo: credit.addi_info,

        bankName: credit.bankName,
        bankBranchName: credit.bankBranchName,
        bankAccountName: credit.bankAccountName,
        bankAccountNo: credit.bankAccNum,
        bankManagerName: credit.bankManagerName,
        bankManagerPhone: credit.bankManagerPhone,
        bankEmail: credit.bankEmail,
        companyNameTR: credit.company__name,
        contactNameTR: credit.contact__name,
        addressTR: credit.address2,
        companyPhone: credit.phone2,
        dateAccountOpenedTR: credit.account_opened,
        creditLimitTR: credit.credit_date_limit,
        customerPhone: credit.phone3,
        storeFile: credit.storeFileName ? `${baseURL}${credit.storeFileName}` : null,
        birFile: credit.birFile ? `${baseURL}${credit.birFile}` : null,
        businessPermitFile: credit.mayorFileName ? `${baseURL}${credit.mayorFileName}` : null,
        dtiSecRegistrationFile: credit.dtiFileName ? `${baseURL}${credit.dtiFileName}` : null,
        bankStatementPassbookFile: credit.bankFileName ? `${baseURL}${credit.bankFileName}` : null,
        bankAuthorizationFile: credit.bankAuthorizationFile ? `${baseURL}${credit.bankAuthorizationFile}` : null,
        otherFile: credit.otherFileName ? `${baseURL}${credit.otherFileName}` : null,
        creditApprovalFile: credit.approvalFileName ? `${baseURL}${credit.approvalFileName}` : null,
        govIdFile: credit.govFileName ? `${baseURL}${credit.govFileName}` : null,
        tinFile: credit.tinFileName ? `${baseURL}${credit.tinFileName}` : null,

        agentEmail: credit.agent_email,
        agentCode: credit.agent_code,

        owner_name: credit.owner_name,
        owner_mobile_number: credit.owner_mobile_number,
      };

      res.status(200).json({ success: true, creditApplication });
    })
    .catch((err) => {
      next(err);
    });
};
