package cmdCreate

import (
	"bytes"
	"encoding/json"
	"fmt"
	"kode-starter/config"
	"kode-starter/structures"
	"kode-starter/utils"
	"log"
	"net/http"
	"os"
	"os/exec"

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

var token, org, name, private, description string

var CreateCmd = &cobra.Command{
	Use:   "create",
	Short: "Create Github project",
	Long:  `A simple CLI app to create a startup project on Github`,
	Run: func(cmd *cobra.Command, args []string) {

		config.SetInformations(cmd, args)

		err := CreateProject()
		if err != nil {
			fmt.Println("Error:", err)
			return
		}
	},
}

func CreateProject() error {

	godotenv.Load()

	fmt.Printf("Token: %s\n", config.GetToken())
	fmt.Printf("Name: %s\n", config.GetCreateName())
	fmt.Printf("Description: %s\n", config.GetCreateDescription())
	fmt.Printf("Private: %s\n", config.GetCreatePrivate())
	fmt.Printf("Org: %s\n", config.GetCreateOrganisation())

	// Construct POST data
	data := structures.Project{
		Name:        name,
		Description: description,
		Private:     private == "true",
	}

	data.Name = config.GetCreateName()
	data.Description = config.GetCreateDescription()

	fmt.Println("Structure Name:" + data.Name)

	// Make API request to create Github project
	jsonData, _ := json.Marshal(data)

	req, err := http.NewRequest("POST",
		fmt.Sprintf("%s/%s/repos", config.GetUrlApiOrgs(), config.GetCreateOrganisation()),
		bytes.NewBuffer(jsonData))
	req.Header.Set("Authorization", "token "+config.GetToken())
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		log.Fatalln(err)
	}

	var dataReceived structures.GitOrgsRepoResponse
	err = json.NewDecoder(res.Body).Decode(&dataReceived)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(dataReceived)
	fmt.Printf("==> Created project '%s' URL: '%s'\n", name, dataReceived.CloneURL)

	defer res.Body.Close()

	// Create directory of the project
	fmt.Println("==> Creating directory...")
	utils.CreateDir(name)
	fmt.Println("==> Created directory")

	// Change to project directory
	err = os.Chdir(name)
	if err != nil {
		log.Fatal(err)
	}

	isCreated := CreateReadme(name, description, "BC", "")
	if isCreated {
		fmt.Println("==> Created README.md")
	}

	// Git commands
	gitCmd := exec.Command("git", "init")
	err = gitCmd.Run()
	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Printf("==> Initialized empty Git repository in %s\n", name)
	}

	gitCmd = exec.Command("git", "checkout", "-b", "main")
	err = gitCmd.Run()
	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Println("==> Switched to a new branch 'main'")
	}

	gitCmd = exec.Command("git", "add", "-A")
	err = gitCmd.Run()
	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Println("==> Switched to a new branch 'main'")
	}

	gitCmd = exec.Command("git", "commit", "-m", "first commit from project creator !")
	err = gitCmd.Run()
	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Println("==> first commit from Kode-Creator !")
	}

	// Get project info from API response
	var project structures.Project
	json.NewDecoder(res.Body).Decode(&project)
	fmt.Println(project)

	return nil
}
