package model

import (
	Connection "cf-experian/module_server/handlers/Modules/Connection"
	Schema "cf-experian/module_server/handlers/Schema"
	"database/sql"
	"fmt"

	log "github.com/rs/zerolog/log"
)

func Save(creditReport Schema.CreditReport) {

	db, err := Connection.DBConE()

	log.Print("connection started")
	if err != nil {
		log.Print("Connection Error# %s", err.Error())
		panic(err.Error())
	}

	is_exist, err := db.Query("select id from credit_report where application_id = ? and applicant_type=?", creditReport.ApplicationID, creditReport.Applicant_type)

	var creditReportID int64
	var errCheck error
	for is_exist.Next() {
		err = is_exist.Scan(&creditReportID)
		if err != nil {
			panic(err.Error())
		}
		log.Print("Transaction Fetched")
		log.Print(creditReportID)
	}

	if creditReportID > 0 {
		log.Print("connection started: insert")
		_, err := db.Exec("UPDATE credit_report set Score = ?, NoOfActiveAccounts = ?, activeCreditCardLimit = ?, sanctionAmount = ?, TotalPastDue = ?, Past12Months = ?, Past24Months = ?, TotalEnquiry = ?, zeroBalanceAccount = ?, pastDueAccount = ?, VoterID = ?, contactInfoList = ?, PANIdsList = ?, AddressInfoList = ?, updated_at = ?, NationalIdsList = ?, DateOfBirth = ?, bureau = ?, panValidation = ? where application_id = ? and applicant_type = ?", creditReport.Score, creditReport.NoOfActiveAccounts, creditReport.ActiveCreditCardLimit, creditReport.SanctionAmount, creditReport.TotalPastDue, creditReport.Past12Months, creditReport.Past24Months, creditReport.TotalEnquiry, creditReport.ZeroBalanceAccount, creditReport.PastDueAccount, creditReport.VoterID, creditReport.ContactInfoList, creditReport.PANIdsList, creditReport.AddressInfoList, creditReport.Created_at, creditReport.NationalIdsList, creditReport.DateOfBirth, creditReport.Bureau, creditReport.PanValidation, creditReport.ApplicationID, creditReport.Applicant_type)
		if err != nil {
			log.Print(err.Error())
			panic(err.Error())
		}

		log.Print(fmt.Sprint("Updated: ", creditReportID))
	} else {
		log.Print("connection started: insert")
		credit_report_results, err := db.Exec("INSERT INTO credit_report (application_id, Score, NoOfActiveAccounts, activeCreditCardLimit, sanctionAmount, TotalPastDue, Past12Months, Past24Months, TotalEnquiry, zeroBalanceAccount, pastDueAccount, VoterID, contactInfoList, PANIdsList, AddressInfoList, applicant_type, created_at, NationalIdsList, DateOfBirth, bureau, panValidation) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", creditReport.ApplicationID, creditReport.Score, creditReport.NoOfActiveAccounts, creditReport.ActiveCreditCardLimit, creditReport.SanctionAmount, creditReport.TotalPastDue, creditReport.Past12Months, creditReport.Past24Months, creditReport.TotalEnquiry, creditReport.ZeroBalanceAccount, creditReport.PastDueAccount, creditReport.VoterID, creditReport.ContactInfoList, creditReport.PANIdsList, creditReport.AddressInfoList, creditReport.Applicant_type, creditReport.Created_at, creditReport.NationalIdsList, creditReport.DateOfBirth, creditReport.Bureau, creditReport.PanValidation)
		if err != nil {
			log.Print(err.Error())
			panic(err.Error())
		}

		creditReportID, errCheck = credit_report_results.LastInsertId()
		if errCheck != nil {
			log.Print("Queue Insert: ", errCheck.Error())
		}
		log.Print(fmt.Sprint("inserted: ", creditReportID))

		for _, row := range creditReport.Foir {

			foir_results, err := db.Exec("INSERT INTO foir (application_id, credit_id, AccountType, Institution, OwnershipType, ApprovedAmount, Balance, InterestRate, RepaymentTenure, InstallmentAmount, cc_loan, isOpened, DateOpened, DateClosed, LastPaymentDate, LastPayment, PastDueAmount, dpd, applicant_type, created_by, created_at, ReportedDate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", row.ApplicationID, creditReportID, row.AccountType, row.Institution, row.OwnershipType, row.ApprovedAmount, row.Balance, row.InterestRate, row.RepaymentTenure, row.InstallmentAmount, row.CC_loan, row.IsOpened, row.DateOpened, NewNullString(row.DateClosed), NewNullString(row.LastPaymentDate), row.LastPayment, row.PastDueAmount, row.DPD, row.ApplicantType, row.CreatedBy, row.CreatedAt, row.ReportedDate)
			if err != nil {
				log.Print(err.Error())
				panic(err.Error())
			}

			foir_id, err := foir_results.LastInsertId()
			log.Print(foir_id)

		}

	}

	//     log.Print(fmt.Sprint("inserted: ", creditReportID))

	defer db.Close()
}

func NewNullString(s string) sql.NullString {
	if len(s) == 0 {
		return sql.NullString{}
	}
	return sql.NullString{
		String: s,
		Valid:  true,
	}
}
