package main

import (
	"context"
	"database/sql"
	"encoding/csv"
	"flag"
	"fmt"
	"os"

	_ "github.com/go-sql-driver/mysql"
	"github.com/stephenafamo/bob"
	"gitlab.artefactual.com/dcosme/am-scripts/database/mcp/models"
)

var (
	csvPath         = flag.String("csv", "aips.csv", "Path to the CSV file containing AIP names")
	mysqlConnString = flag.String("mysql", "root:12345@tcp(localhost:62001)/SS?parseTime=true", "mysql connection string")
)

func main() {
	flag.Parse()
	file, err := os.Open(*csvPath)
	assertNoErr(err)
	records, err := csv.NewReader(file).ReadAll()
	assertNoErr(err)

	result, err := os.OpenFile("aip_names.txt", os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
	assertNoErr(err)

	db := openDB(*mysqlConnString)
	bobDB := bob.NewDB(db)

	for _, record := range records {
		q := models.LocationsPackages.Query()
		like := fmt.Sprintf("%%%s%%", record[0])
		q.Apply(models.SelectWhere.LocationsPackages.CurrentPath.Like(like))
		res, err := q.All(context.Background(), bobDB)
		assertNoErr(err)
		for _, r := range res {
			fmt.Println("AIP Found: " + r.CurrentPath)
			_, err = result.WriteString(r.CurrentPath + "\n")
		}
	}
}

func assertNoErr(err error) {
	if err != nil {
		panic(err)
	}
}

func openDB(connStr string) *sql.DB {
	db, err := sql.Open("mysql", connStr)
	assertNoErr(err)
	err = db.Ping()
	assertNoErr(err)
	return db
}
