package main

import (
	"encoding/csv"
	"fmt"
	"io"
	"os"
	"sync"

	"github.com/gocarina/gocsv"
)

type (
	CompanyOld struct {
		IDEmpregador     int    `csv:"id_empregador"` // Corrected to match the CSV header "id_empregador"
		NMEMpregador     string `csv:"nm_empregador"` // Corrected to match the CSV header "nm_empregador"
		DSDescricao      string `csv:"ds_descricao"`  // Corrected to match the CSV header "ds_descricao"
		CDTipo           string `csv:"cd_tipo"`       // Corrected to match the CSV header "cd_tipo"
		NRCpfCnpj        string `csv:"nr_cpf_cnpj"`   // Corrected to match the CSV header "nr_cpf_cnpj"
		DSEndereco       string `csv:"ds_endereco"`   // Corrected to match the CSV header "ds_endereco"
		NRCep            string `csv:"nr_cep"`        // Corrected to match the CSV header "nr_cep"
		NRTelResidencial string `csv:"nr_tel_residencial"`
		NRTelCelular     string `csv:"nr_tel_celular"`
		IDBairro         string `csv:"id_bairro"`
		DSOutroLugar     string `csv:"ds_outro_lugar"`
		DSEmail          string `csv:"ds_email"`
		DSSenha          string `csv:"ds_senha"`
		NMContato        string `csv:"nm_contato"`
		DSLogotipo       string `csv:"ds_logotipo"`
		DTCadastro       string `csv:"dt_cadastro"`
		DTAlteracao      string `csv:"dt_alteracao"` // Corrected to match the CSV header "dt_alteracao"
		SNAtivo          string `csv:"sn_ativo"`     // Corrected to match the CSV header "sn_ativo"
	}
	Company struct {
		ID              int    `csv:"id"`
		CorporateName   string `csv:"corporate_name"`
		Description     string `csv:"description"`
		Cnpj            string `csv:"cnpj"`
		CDTipo          string `csv:"cd_tipo"`
		Address         string `csv:"address"`
		ZipCode         string `csv:"zip_code"`
		Telephone       string `csv:"telephone"`
		Cellphone       string `csv:"cellphone"`
		NeighbourhoodID string `csv:"neighbourhood_id"`
		Email           string `csv:"email"`
		Password        string `csv:"password"`
		ContactName     string `csv:"contact_name"`
		Logo            string `csv:"logo"`
		CreatedAt       string `csv:"created_at"`
		UpdatedAt       string `csv:"updated_at"`
		Active          string `csv:"active"`
	}
)

func ExecCompanies(wg *sync.WaitGroup) {
	defer wg.Done()
	records := extractCompaniesOld()
	createCompaniesCsv(records)
}

func extractCompaniesOld() []CompanyOld {
	fmt.Println(Yellow + "Extracting companies" + Reset)
	csvFile, err := os.Open("files/TB_SOPA_BC_EMPREGADOR.csv")
	if err != nil {
		panic(err)
	}
	defer csvFile.Close()
	// Create a new CSV reader with tab as the delimiter
	reader := csv.NewReader(csvFile)
	reader.Comma = ','
	var records []CompanyOld
	if err := gocsv.UnmarshalCSV(reader, &records); err != nil {
		fmt.Println(Red + err.Error() + Reset)
		panic(err)
	}
	if len(records) == 0 {
		panic("No records found")
	}
	return records

}

func createCompaniesCsv(records []CompanyOld) {
	file, err := os.Create(basePath + "companies.csv")
	if err != nil {
		fmt.Println(Red + err.Error() + Reset)
		panic(err)
	}
	defer file.Close()

	var companies []*Company
	for _, record := range records {
		cleanedDescription := replaceCharacter("\n", " ", record.DSDescricao)
		cleanedDescription = replaceCharacter("\r", "", cleanedDescription)
		company := &Company{
			ID:              record.IDEmpregador,
			CorporateName:   record.NMEMpregador,
			Description:     cleanedDescription,
			Cnpj:            record.NRCpfCnpj,
			CDTipo:          record.CDTipo,
			Address:         record.DSEndereco,
			ZipCode:         record.NRCep,
			Telephone:       record.NRTelResidencial,
			Cellphone:       record.NRTelCelular,
			NeighbourhoodID: record.IDBairro,
			Email:           record.DSEmail,
			Password:        record.DSSenha,
			ContactName:     record.NMContato,
			Logo:            record.DSLogotipo,
			CreatedAt:       record.DTCadastro,
			UpdatedAt:       record.DTAlteracao,
			Active:          record.SNAtivo,
		}
		companies = append(companies, company)
	}

	gocsv.SetCSVWriter(func(out io.Writer) *gocsv.SafeCSVWriter {
		writer := csv.NewWriter(out)
		writer.Comma = '\t'
		return gocsv.NewSafeCSVWriter(writer)
	})
	err = gocsv.MarshalFile(&companies, file)
	if err != nil {
		fmt.Println(Red + err.Error() + Reset)
		panic(err)
	}

	fmt.Println(Green + "Successfully created CSV file with the processed companies." + Reset)
}
