package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"strings"

	"gitlab.com/mbugroup/lti-api.git/internal/apikeys"
	"gitlab.com/mbugroup/lti-api.git/internal/config"
	"gitlab.com/mbugroup/lti-api.git/internal/database"
)

func main() {
	if len(os.Args) < 2 {
		usage()
		os.Exit(1)
	}

	db := database.Connect(config.DBHost, config.DBName)
	service := apikeys.NewService(db)
	ctx := context.Background()

	switch os.Args[1] {
	case "create":
		fs := flag.NewFlagSet("create", flag.ExitOnError)
		name := fs.String("name", "dashboard-read-api", "integration client name")
		environment := fs.String("env", config.AppEnv, "environment label")
		permissions := fs.String("permissions", "", "comma separated permission codes")
		allArea := fs.Bool("all-area", true, "grant all areas")
		areaIDs := fs.String("area-ids", "", "comma separated area ids")
		allLocation := fs.Bool("all-location", true, "grant all locations")
		locationIDs := fs.String("location-ids", "", "comma separated location ids")
		fs.Parse(os.Args[2:])

		permissionCodes := apikeys.DefaultDashboardPermissions()
		if strings.TrimSpace(*permissions) != "" {
			permissionCodes = splitCSV(*permissions)
		}

		issued, err := service.Create(ctx, apikeys.CreateInput{
			Name:            *name,
			Environment:     *environment,
			PermissionCodes: permissionCodes,
			AllArea:         *allArea,
			AreaIDs:         parseUintCSV(*areaIDs),
			AllLocation:     *allLocation,
			LocationIDs:     parseUintCSV(*locationIDs),
		})
		if err != nil {
			panic(err)
		}

		fmt.Printf("name: %s\n", issued.Record.Name)
		fmt.Printf("environment: %s\n", issued.Record.Environment)
		fmt.Printf("prefix: %s\n", issued.Record.KeyPrefix)
		fmt.Printf("status: %s\n", issued.Record.Status)
		fmt.Printf("api_key: %s\n", issued.Key)
	case "list":
		fs := flag.NewFlagSet("list", flag.ExitOnError)
		environment := fs.String("env", "", "filter by environment")
		fs.Parse(os.Args[2:])

		records, err := service.List(ctx, *environment)
		if err != nil {
			panic(err)
		}

		for _, record := range records {
			fmt.Printf("%s\t%s\t%s\t%s\tareas=%t\tlocations=%t\n",
				record.Environment,
				record.KeyPrefix,
				record.Status,
				record.Name,
				record.AllArea,
				record.AllLocation,
			)
		}
	case "revoke":
		fs := flag.NewFlagSet("revoke", flag.ExitOnError)
		environment := fs.String("env", config.AppEnv, "environment label")
		prefix := fs.String("prefix", "", "key prefix to revoke")
		fs.Parse(os.Args[2:])

		if err := service.Revoke(ctx, *environment, *prefix); err != nil {
			panic(err)
		}
		fmt.Printf("revoked %s/%s\n", *environment, *prefix)
	default:
		usage()
		os.Exit(1)
	}
}

func usage() {
	fmt.Println("usage:")
	fmt.Println("  go run ./cmd/api-key create [flags]")
	fmt.Println("  go run ./cmd/api-key list [flags]")
	fmt.Println("  go run ./cmd/api-key revoke -env <environment> -prefix <prefix>")
}

func splitCSV(raw string) []string {
	if strings.TrimSpace(raw) == "" {
		return nil
	}
	parts := strings.Split(raw, ",")
	out := make([]string, 0, len(parts))
	for _, part := range parts {
		part = strings.TrimSpace(part)
		if part != "" {
			out = append(out, part)
		}
	}
	return out
}

func parseUintCSV(raw string) []uint {
	parts := splitCSV(raw)
	if len(parts) == 0 {
		return nil
	}

	values := make([]uint, 0, len(parts))
	for _, part := range parts {
		var value uint
		if _, err := fmt.Sscanf(part, "%d", &value); err == nil && value > 0 {
			values = append(values, value)
		}
	}
	return values
}
