package cmdLists

import (
	"encoding/json"
	"fmt"
	"io"
	"kode-starter/config"
	"kode-starter/utils"
	"net/http"
	"strconv"

	"github.com/joho/godotenv"
	"github.com/spf13/cobra"
)

// This is a variable declaration that creates a new Cobra command called `ListCmd`. The command has a
// `Use` field that specifies the name of the command, a `Short` field that provides a brief
// description of the command, and a `Long` field that provides a more detailed description of the
// command. The `Run` field is a function that is executed when the command is run. It sets some
// configuration information based on the command line arguments, and then either lists the projects
// for a specified organization or lists all organizations, depending on the command line arguments.
var ListCmd = &cobra.Command{
	Use:   "list",
	Short: "List Github, Gitea orgs, project",
	Long:  `A simple CLI app to list Github, Gitea orgs, project`,
	Run: func(cmd *cobra.Command, args []string) {

		config.SetInformations(cmd, args)

		// if -o flag is set, list projects for that org
		if config.GetListOrganisationFlag() {
			if !config.GetJsonFlag() {
				utils.PrintHeader()
				fmt.Println("\nList projects for org: " + config.GetListOrganisation() + "\n")
				fmt.Println(utils.CreateLine(6))
			}
			projects, err := ListProjects(config.GetListOrganisation())
			if err != nil {
				fmt.Println("Error:", err)
				return
			}
			for _, project := range projects {
				fmt.Print(project)
			}
		} else {
			orgs, err := ListOrganization()
			if err != nil {
				fmt.Println("Error:", err)
				return
			}
			if !config.GetJsonFlag() {
				fmt.Println("\nList of Organizations :")
				fmt.Println(utils.CreateLine(4))
			}
			for _, org := range orgs {
				fmt.Print(org)
			}
		}

	},
}

// The ListOrganization function retrieves a list of organizations from a specified URL and returns
// their names and URLs.
func ListOrganization() ([]string, error) {
	godotenv.Load()

	if config.GetVerboseFlag() {
		fmt.Println("execute ListOrganization ...")
		fmt.Println("URL: " + config.GetUrlApiOrgs())
		fmt.Println("Token: " + config.GetToken())
	}
	body := UrlGetBody(config.GetUrlApiOrgs())
	if config.GetJsonFlag() {
		return utils.BytesToStrings(body), nil
	} else {

		var orgs []map[string]interface{}
		err := json.Unmarshal(body, &orgs)
		if err != nil {
			return nil, err
		} else {
			var orgNames []string
			for i, org := range orgs {
				nb := strconv.FormatInt(int64(i+1), 10)
				orgName := fmt.Sprintf("%s", org["username"])
				orgUrl := fmt.Sprintf("[  %s/%s  ]\n", config.GetUrlBase(), org["username"])
				orgNames = append(
					orgNames,
					utils.PadString(nb, 4),
					utils.PadString(orgName, 30),
					orgUrl)
			}
			return orgNames, nil
		}
	}
}

// This function lists the projects of a given organization and returns their names and clone URLs.
func ListProjects(org string) ([]string, error) {
	godotenv.Load()

	if config.GetVerboseFlag() {
		fmt.Println("execute ListProjects ...")
		fmt.Println("URL: " + config.GetUrlApiOrgs())
		fmt.Println("Token: " + config.GetToken())
	}

	body := UrlGetBody(config.GetUrlApiOrgs() + "/" + org + "/repos")
	if config.GetJsonFlag() {
		return utils.BytesToStrings(body), nil
	} else {
		var prjs []map[string]interface{}
		err := json.Unmarshal(body, &prjs)
		if err != nil {
			return nil, err
		} else {
			var orgNames []string

			for i, prj := range prjs {
				nb := strconv.FormatInt(int64(i+1), 10)
				projectName := fmt.Sprintf("%s", prj["name"])
				cloneUrl := fmt.Sprintf("[  %s  ]\n", prj["clone_url"])
				orgNames = append(
					orgNames,
					utils.PadString(nb, 4),
					utils.PadString(projectName, 40),
					cloneUrl,
				)
			}
			return orgNames, nil
		}
	}
}

// This function sends a GET request to a specified URL with authorization and content-type headers,
// and returns the response body as a byte array.
func UrlGetBody(url string) []byte {

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)

	}
	req.Header.Set("Authorization", "token "+config.GetToken())
	req.Header.Set("Content-Type", "application/json")
	// fmt.Println(req.Header.Get("Authorization"))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)

	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)

	if err != nil {
		fmt.Println("Error reading response body:", err)

	}
	return body
}
