package services

import (
	"log"
	"ticket-pimp/internal/domain"
	"ticket-pimp/internal/helpers"
	"time"
)

type Git struct {
	*CommonClient
}

type IGit interface {
	CreateRepo(name string) (*domain.Git, error)
}

func NewGit(base, token string) *Git {
	headers := map[string]string{
		"Accept":               "application/vnd.github+json",
		"Authorization":        "Token " + token,
		"X-GitHub-Api-Version": "2022-11-28",
		"Content-Type":         "application/json",
	}

	client := NewClient().
		SetTimeout(5 * time.Second).
		SetCommonHeaders(headers).
		SetBaseURL(base)

	return &Git{
		CommonClient: &CommonClient{client},
	}
}

func (gb *Git) CreateRepo(name string) (*domain.Git, error) {
	//Create git repository with iGit interface;
	repo, err := gb.newRepo(name)
	if err != nil {
		return nil, err
	}

	//Set 'apps' as collaborator to created repository;
	_, err = gb.defaultGroupAsCollaborator(repo)
	if err != nil {
		return nil, err
	}

	return repo, nil
}

type request struct {
	Name    string `json:"name"`
	Private bool   `json:"private"`
}

type permissionRequest struct {
	Perm string `json:"permission"`
}

func (gb *Git) newRepo(name string) (*domain.Git, error) {
	name = helpers.GitNaming(name)

	payload := request{
		Name:    name,
		Private: true,
	}

	var git domain.Git

	resp, _ := gb.R().
		SetBody(&payload).
		SetSuccessResult(&git).
		Post("/orgs/mobilerino/repos")

	if resp.Err != nil {
		log.Print(resp.Status, resp.Err)
		return nil, resp.Err
	}

	return &git, nil
}

func (gb *Git) defaultGroupAsCollaborator(git *domain.Git) (*domain.Git, error) {

	payload := permissionRequest{
		Perm: "push",
	}

	///orgs/manurlerino/teams/devs/repos/manurlerino/x
	respURL := "/orgs/mobilerino/teams/devs/repos/mobilerino/" + git.Name

	resp, _ := gb.R().
		SetBody(&payload).
		Put(respURL)

	if resp.Err != nil {
		log.Print(resp.Err)
		return nil, resp.Err
	}

	return git, nil
}
