package main

import (
	"context"
	"fmt"
	"os"

	"github.com/jackc/pgx/v5"
)

func main() {
	dbURL := "postgres://user:pass@localhost:54322/photum-v2?sslmode=disable"
	conn, err := pgx.Connect(context.Background(), dbURL)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to connect: %v\n", err)
		os.Exit(1)
	}
	defer conn.Close(context.Background())

	// 1. Get IDs of garbage years
	rows, err := conn.Query(context.Background(), "SELECT id, ano_semestre FROM anos_formaturas WHERE ano_semestre !~ '^\\d{4}\\.\\d+$'")
	if err != nil {
		fmt.Fprintf(os.Stderr, "Select garbage failed: %v\n", err)
		os.Exit(1)
	}
	defer rows.Close()

	var ids []string
	for rows.Next() {
		var id, val string
		rows.Scan(&id, &val)
		ids = append(ids, id)
		fmt.Printf("Found garbage year: %s (%s)\n", val, id)
	}
	rows.Close()

	if len(ids) > 0 {
		// 2. Delete dependencies in cadastro_fot
		fmt.Println("Deleting dependencies in cadastro_fot...")
		_, err = conn.Exec(context.Background(), "DELETE FROM cadastro_fot WHERE ano_formatura_id = ANY($1)", ids)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Delete dependencies failed: %v\n", err)
			os.Exit(1)
		}

		// 3. Delete the years
		fmt.Println("Deleting garbage years...")
		ct, err := conn.Exec(context.Background(), "DELETE FROM anos_formaturas WHERE id = ANY($1)", ids)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Delete years failed: %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("Deleted %d garbage rows.\n", ct.RowsAffected())
	} else {
		fmt.Println("No garbage found.")
	}
}
