package zonerecs

import (
	"github.com/DNSControl/dnscontrol/v5/models"
)

// CorrectZoneRecords calls both GetZoneRecords, does any
// post-processing, and then calls GetZoneRecordsCorrections.  The
// name sucks because all the good names were taken.
func CorrectZoneRecords(driver models.DNSProvider, dc *models.DomainConfig) ([]*models.Correction, []*models.Correction, int, error) {
	existingRecords, err := driver.GetZoneRecords(dc)
	if err != nil {
		return nil, nil, 0, err
	}

	// Copy dc so that any correction code that wants to
	// modify the records may. For example, if the provider only
	// supports certain TTL values, it will adjust the ones in
	// dc.Records.
	dc, err = dc.Copy()
	if err != nil {
		return nil, nil, 0, err
	}

	everything, actualChangeCount, err := driver.GetZoneRecordsCorrections(dc, existingRecords)
	reports, corrections := splitReportsAndCorrections(everything)
	return reports, corrections, actualChangeCount, err
}

func splitReportsAndCorrections(everything []*models.Correction) (reports, corrections []*models.Correction) {
	for i := range everything {
		if everything[i].F == nil {
			reports = append(reports, everything[i])
		} else {
			corrections = append(corrections, everything[i])
		}
	}
	return reports, corrections
}
