package gitea

import (
	"encoding/json"
	"gitea-page/internal/config"
	"gitea-page/internal/git"
	"gitea-page/internal/promote"
	"github.com/rs/zerolog/log"
	"io"
	"net/http"
	"time"
)

type webhookContent struct {
	Ref string `json:"ref"`
	Before string `json:"before"`
	Repository webhookContentRepository `json:"repository"`
}

type webhookContentRepository struct {
	Name string `json:"name"`
	Owner webhookContentRepositoryOwner `json:"owner"`
	SSHUrl string `json:"ssh_url"`
}

type webhookContentRepositoryOwner struct {
	Username string `json:"username"`
}

type GiteaWebhook struct {
	Config config.GiteaPagesConfig
	Git git.GitHandler
	Promoter promote.Promote
}

func (g GiteaWebhook) WebhookEndpoint(w http.ResponseWriter, r *http.Request)  {
	log.Debug().Msg("Webhook Endpoint called")

	body, err := io.ReadAll(r.Body)
	if err != nil {
		log.Warn().Err(err).Msg("Cant get request Body from Request")
		w.WriteHeader(400)
		return
	}

	hook := webhookContent{}
	err = json.Unmarshal(body, &hook)
	if err != nil {
		log.Warn().Err(err).Msg("Cant pars request")
		w.WriteHeader(400)
		return
	}

	log.Debug().Interface("hook", hook).Msg("Webhook parsed")

	if hook.Ref != g.Config.Branch {
		return
	}
	go func() {
		time.Sleep(3 * time.Second)
		g.updateServer(hook)
	}()

	w.WriteHeader(201)
}

func (g GiteaWebhook) updateServer(hook webhookContent) {
	log.Debug().Msg("Update Server")
	g.Git.GetRepository(hook.Repository.Name, hook.Repository.Owner.Username, hook.Repository.SSHUrl)
	g.Promoter.PromoteRepo(hook.Repository.Name, hook.Repository.Owner.Username)
	log.Debug().Msg("Update Server done")
}