//
// Copyright 2021, Sander van Harmelen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package gitlab

import (
	"encoding/json"
	"io"
	"net/http"
)

type (
	TopicsServiceInterface interface {
		// ListTopics returns a list of project topics in the GitLab instance ordered
		// by number of associated projects.
		//
		// GitLab API docs: https://docs.gitlab.com/api/topics/#list-topics
		ListTopics(opt *ListTopicsOptions, options ...RequestOptionFunc) ([]*Topic, *Response, error)
		// GetTopic gets a project topic by ID.
		//
		// GitLab API docs: https://docs.gitlab.com/api/topics/#get-a-topic
		GetTopic(topic int64, options ...RequestOptionFunc) (*Topic, *Response, error)
		// CreateTopic creates a new project topic.
		//
		// GitLab API docs:
		// https://docs.gitlab.com/api/topics/#create-a-project-topic
		CreateTopic(opt *CreateTopicOptions, options ...RequestOptionFunc) (*Topic, *Response, error)
		// UpdateTopic updates a project topic. Only available to administrators.
		//
		// To remove a topic avatar set the TopicAvatar.Filename to an empty string
		// and set TopicAvatar.Image to nil.
		//
		// GitLab API docs:
		// https://docs.gitlab.com/api/topics/#update-a-project-topic
		UpdateTopic(topic int64, opt *UpdateTopicOptions, options ...RequestOptionFunc) (*Topic, *Response, error)
		// DeleteTopic deletes a project topic. Only available to administrators.
		//
		// GitLab API docs:
		// https://docs.gitlab.com/api/topics/#delete-a-project-topic
		DeleteTopic(topic int64, options ...RequestOptionFunc) (*Response, error)
	}

	// TopicsService handles communication with the topics related methods
	// of the GitLab API.
	//
	// GitLab API docs: https://docs.gitlab.com/api/topics/
	TopicsService struct {
		client *Client
	}
)

var _ TopicsServiceInterface = (*TopicsService)(nil)

// Topic represents a GitLab project topic.
//
// GitLab API docs: https://docs.gitlab.com/api/topics/
type Topic struct {
	ID                 int64  `json:"id"`
	Name               string `json:"name"`
	Title              string `json:"title"`
	Description        string `json:"description"`
	TotalProjectsCount uint64 `json:"total_projects_count"`
	AvatarURL          string `json:"avatar_url"`
}

func (t Topic) String() string {
	return Stringify(t)
}

// ListTopicsOptions represents the available ListTopics() options.
//
// GitLab API docs: https://docs.gitlab.com/api/topics/#list-topics
type ListTopicsOptions struct {
	ListOptions
	Search *string `url:"search,omitempty" json:"search,omitempty"`
}

func (s *TopicsService) ListTopics(opt *ListTopicsOptions, options ...RequestOptionFunc) ([]*Topic, *Response, error) {
	res, resp, err := do[[]*Topic](s.client,
		withMethod(http.MethodGet),
		withPath("topics"),
		withAPIOpts(opt),
		withRequestOpts(options...),
	)
	if err != nil {
		return nil, resp, err
	}
	return res, resp, nil
}

func (s *TopicsService) GetTopic(topic int64, options ...RequestOptionFunc) (*Topic, *Response, error) {
	res, resp, err := do[*Topic](s.client,
		withMethod(http.MethodGet),
		withPath("topics/%d", topic),
		withAPIOpts(nil),
		withRequestOpts(options...),
	)
	if err != nil {
		return nil, resp, err
	}
	return res, resp, nil
}

// CreateTopicOptions represents the available CreateTopic() options.
//
// GitLab API docs:
// https://docs.gitlab.com/api/topics/#create-a-project-topic
type CreateTopicOptions struct {
	Name        *string      `url:"name,omitempty" json:"name,omitempty"`
	Title       *string      `url:"title,omitempty" json:"title,omitempty"`
	Description *string      `url:"description,omitempty" json:"description,omitempty"`
	Avatar      *TopicAvatar `url:"-" json:"-"`
}

// TopicAvatar represents a GitLab topic avatar.
type TopicAvatar struct {
	Filename string
	Image    io.Reader
}

// MarshalJSON implements the json.Marshaler interface.
func (a *TopicAvatar) MarshalJSON() ([]byte, error) {
	if a.Filename == "" && a.Image == nil {
		return []byte(`""`), nil
	}
	type alias TopicAvatar
	return json.Marshal((*alias)(a))
}

func (s *TopicsService) CreateTopic(opt *CreateTopicOptions, options ...RequestOptionFunc) (*Topic, *Response, error) {
	reqOpts := []doOption{
		withMethod(http.MethodPost),
		withPath("topics"),
		withAPIOpts(opt),
		withRequestOpts(options...),
	}
	if opt.Avatar != nil {
		reqOpts = append(reqOpts, withUpload(opt.Avatar.Image, opt.Avatar.Filename, UploadAvatar))
	}
	return do[*Topic](s.client, reqOpts...)
}

// UpdateTopicOptions represents the available UpdateTopic() options.
//
// GitLab API docs:
// https://docs.gitlab.com/api/topics/#update-a-project-topic
type UpdateTopicOptions struct {
	Name        *string      `url:"name,omitempty" json:"name,omitempty"`
	Title       *string      `url:"title,omitempty" json:"title,omitempty"`
	Description *string      `url:"description,omitempty" json:"description,omitempty"`
	Avatar      *TopicAvatar `url:"-" json:"avatar,omitempty"`
}

func (s *TopicsService) UpdateTopic(topic int64, opt *UpdateTopicOptions, options ...RequestOptionFunc) (*Topic, *Response, error) {
	reqOpts := []doOption{
		withMethod(http.MethodPut),
		withPath("topics/%d", topic),
		withAPIOpts(opt),
		withRequestOpts(options...),
	}
	if opt.Avatar != nil && (opt.Avatar.Filename != "" || opt.Avatar.Image != nil) {
		reqOpts = append(reqOpts, withUpload(opt.Avatar.Image, opt.Avatar.Filename, UploadAvatar))
	}
	return do[*Topic](s.client, reqOpts...)
}

func (s *TopicsService) DeleteTopic(topic int64, options ...RequestOptionFunc) (*Response, error) {
	_, resp, err := do[none](s.client,
		withMethod(http.MethodDelete),
		withPath("topics/%d", topic),
		withAPIOpts(nil),
		withRequestOpts(options...),
	)
	return resp, err
}
