package main

import (
	"context"
	"database/sql"
	"encoding/csv"
	"flag"
	"fmt"
	"log"
	"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() {
	err := server()
	assertNoErr(err)

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

	db, err := openDB(*mysqlConnString)
	if err != nil {
		log.Fatal(err)
	}
	bobDB := bob.NewDB(db)

	err = os.RemoveAll("aips-report.csv")
	assertNoErr(err)
	reportFile, err := os.Create("aips-report.csv")
	assertNoErr(err)
	reportWriter := csv.NewWriter(reportFile)

	reportData := make([][]string, len(records))
	for idx, record := range records {
		q := models.LocationsPackages.Query()
		like := fmt.Sprintf("%%%s%%", record)
		q.Apply(models.SelectWhere.LocationsPackages.CurrentPath.Like(like))
		res, err := q.All(context.Background(), bobDB)
		assertNoErr(err)

		row := []string{record[0]}
		for _, r := range res {
			fmt.Println("AIP Found: " + r.CurrentPath)
			row = append(row, r.CurrentPath)
		}
		reportData[idx] = row
	}

	for _, row := range reportData {
		err = reportWriter.Write(row)
		assertNoErr(err)
	}
}

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

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