package common

/*
 * This file is part of Autogits.
 *
 * Copyright © 2024 SUSE LLC
 *
 * Autogits is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 2 of the License, or (at your option) any later
 * version.
 *
 * Autogits is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * Foobar. If not, see <https://www.gnu.org/licenses/>.
 */

import (
	"encoding/json"
	"fmt"
	"io"

	"src.opensuse.org/autogits/common/gitea-generated/models"
)

type Head struct {
	Ref  string
	Repo *Repository
	Sha  string
}

type IssueLabelDetail struct {
	Id          int
	Name        string
	Exclusive   bool
	Is_archived bool
	Color       string
	Description string
	Url         string
}

type PullRequest struct {
	Id     int
	Url    string
	Number int64
	State  string

	Base                Head
	Head                Head
	Labels              []IssueLabelDetail
	Requested_reviewers []*User

	User User
}

type PullRequestWebhookEvent struct {
	Action string
	Number int64

	Pull_Request       *PullRequest
	Repository         *Repository
	Requested_reviewer *User
	Sender             User
}

func (p *PullRequestWebhookEvent) GetAction() string {
	return p.Action
}

func PullRequestLabelFromModel(labels []*models.Label) []IssueLabelDetail {
	l := make([]IssueLabelDetail, len(labels))
	for i := range labels {
		l[i].Id = int(labels[i].ID)
		l[i].Name = labels[i].Name
		l[i].Exclusive = labels[i].Exclusive
		l[i].Is_archived = labels[i].IsArchived
		l[i].Color = labels[i].Color
		l[i].Description = labels[i].Description
		l[i].Url = labels[i].URL
	}

	return l
}

func PullRequestFromModel(pr *models.PullRequest) *PullRequest {
	return &PullRequest{
		Id:     int(pr.ID),
		Url:    pr.URL,
		Number: pr.Index,
		State:  string(pr.State),

		Base: Head{
			Ref:  pr.Base.Ref,
			Sha:  pr.Base.Sha,
			Repo: RepositoryFromModel(pr.Base.Repo),
		},
		Head: Head{
			Ref:  pr.Head.Ref,
			Sha:  pr.Head.Sha,
			Repo: RepositoryFromModel(pr.Head.Repo),
		},
		Labels: PullRequestLabelFromModel(pr.Labels),
		User: *UserFromModel(pr.User),
	}
}

func (h *RequestHandler) parsePullRequest(data io.Reader) (action *PullRequestWebhookEvent, err error) {
	action = new(PullRequestWebhookEvent)
	err = json.NewDecoder(data).Decode(&action)

	if err != nil {
		return nil, fmt.Errorf("Got error while parsing json: %w", err)
	}

	h.Request = &Request{
		Data: action,
		Type: RequestType_PR,
	}
	return
}

func (h *RequestHandler) parsePullRequestSync(data io.Reader) (*PullRequestWebhookEvent, error) {
	return h.parsePullRequest(data)
}
