package main

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

	"github.com/gocarina/gocsv"
)

type (
    ApplicationsOld struct {
        IDCandidato int `csv:"-"`
        IDVaga int `csv:"id_vaga"`
        IDUsuario int `csv:"id_usuario"`
        DTCadastro string `csv:"-"`
    }
    Applications struct {
        JobID int `csv:"job_id"`
        CandidateID int `csv:"candidate_id"`
    }
)

func ExecApplications(wg *sync.WaitGroup) {
    defer wg.Done()

    records := extractApplicationsOld()
    createApplicationsCsv(records)
}

func extractApplicationsOld() []ApplicationsOld {
    fmt.Println(Yellow + "Extracting applications" + Reset)
    csvFile, err := os.Open("files/TB_SOPA_BC_CANDIDATO.csv")
    if err != nil {
        fmt.Println(Red + err.Error() + Reset)
        return nil
    }
    defer csvFile.Close()

    reader := csv.NewReader(csvFile)
    reader.Comma = ','

    var records []ApplicationsOld
    if err := gocsv.UnmarshalCSV(reader, &records); err != nil {
        fmt.Println(Red + err.Error() + Reset)
        return nil
    }
    if len(records) == 0 {
        fmt.Println(Red + "No records found" + Reset)
        return nil
    }
    return records
}

func createApplicationsCsv(records []ApplicationsOld) {
    file, err := os.Create(filepath.Join(basePath, "applications.csv"))
    if err != nil {
        fmt.Println(Red + err.Error() + Reset)
        return
    }
    defer file.Close()

    var applications []*Applications
    for _, record := range records {
        application := &Applications{
            JobID: record.IDVaga,
            CandidateID: record.IDUsuario,
        }
        applications = append(applications, application)
    }

    gocsv.SetCSVWriter(func(out io.Writer) *gocsv.SafeCSVWriter {
        writer := csv.NewWriter(out)
        writer.Comma = '\t' // Ensure tab delimiter is used
        return gocsv.NewSafeCSVWriter(writer)
    })

    err = gocsv.MarshalFile(applications, file)
    if err != nil {
        fmt.Println(Red + err.Error() + Reset)
        return
    }

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