// Copyright 2020 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package github

import (
	"context"
	"fmt"
)

// Workflow represents a repository action workflow.
type Workflow struct {
	ID        *int64     `json:"id,omitempty"`
	NodeID    *string    `json:"node_id,omitempty"`
	Name      *string    `json:"name,omitempty"`
	Path      *string    `json:"path,omitempty"`
	State     *string    `json:"state,omitempty"`
	CreatedAt *Timestamp `json:"created_at,omitempty"`
	UpdatedAt *Timestamp `json:"updated_at,omitempty"`
	URL       *string    `json:"url,omitempty"`
	HTMLURL   *string    `json:"html_url,omitempty"`
	BadgeURL  *string    `json:"badge_url,omitempty"`
}

// Workflows represents a slice of repository action workflows.
type Workflows struct {
	TotalCount *int        `json:"total_count,omitempty"`
	Workflows  []*Workflow `json:"workflows,omitempty"`
}

// WorkflowUsage represents a usage of a specific workflow.
type WorkflowUsage struct {
	Billable *WorkflowBillMap `json:"billable,omitempty"`
}

// WorkflowBillMap represents different runner environments available for a workflow.
// Its key is the name of its environment, e.g. "UBUNTU", "MACOS", "WINDOWS", etc.
type WorkflowBillMap map[string]*WorkflowBill

// WorkflowBill specifies billable time for a specific environment in a workflow.
type WorkflowBill struct {
	TotalMS *int64 `json:"total_ms,omitempty"`
}

// CreateWorkflowDispatchEventRequest represents a request to create a workflow dispatch event.
type CreateWorkflowDispatchEventRequest struct {
	// Ref represents the reference of the workflow run.
	// The reference can be a branch or a tag.
	// Ref is required when creating a workflow dispatch event.
	Ref string `json:"ref"`
	// Inputs represents input keys and values configured in the workflow file.
	// The maximum number of properties is 25.
	// Default: Any default properties configured in the workflow file will be used when `inputs` are omitted.
	Inputs map[string]any `json:"inputs,omitempty"`
	// ReturnRunDetails specifies whether the response should include
	// the workflow run ID and URLs.
	ReturnRunDetails *bool `json:"return_run_details,omitempty"`
}

// WorkflowDispatchRunDetails represents the response from creating
// a workflow dispatch event when ReturnRunDetails is set to true.
type WorkflowDispatchRunDetails struct {
	WorkflowRunID *int64  `json:"workflow_run_id,omitempty"`
	RunURL        *string `json:"run_url,omitempty"`
	HTMLURL       *string `json:"html_url,omitempty"`
}

// WorkflowsPermissions represents the permissions for workflows in a repository.
type WorkflowsPermissions struct {
	RunWorkflowsFromForkPullRequests  *bool `json:"run_workflows_from_fork_pull_requests,omitempty"`
	SendWriteTokensToWorkflows        *bool `json:"send_write_tokens_to_workflows,omitempty"`
	SendSecretsAndVariables           *bool `json:"send_secrets_and_variables,omitempty"`
	RequireApprovalForForkPRWorkflows *bool `json:"require_approval_for_fork_pr_workflows,omitempty"`
}

func (w WorkflowsPermissions) String() string {
	return Stringify(w)
}

// WorkflowsPermissionsOpt specifies options for editing workflows permissions in a repository.
type WorkflowsPermissionsOpt struct {
	RunWorkflowsFromForkPullRequests  bool  `json:"run_workflows_from_fork_pull_requests"`
	SendWriteTokensToWorkflows        *bool `json:"send_write_tokens_to_workflows,omitempty"`
	SendSecretsAndVariables           *bool `json:"send_secrets_and_variables,omitempty"`
	RequireApprovalForForkPRWorkflows *bool `json:"require_approval_for_fork_pr_workflows,omitempty"`
}

// ContributorApprovalPermissions represents the policy that controls
// when fork PR workflows require approval from a maintainer.
type ContributorApprovalPermissions struct {
	ApprovalPolicy string `json:"approval_policy"`
}

func (p ContributorApprovalPermissions) String() string {
	return Stringify(p)
}

// ListWorkflows lists all workflows in a repository.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflows?apiVersion=2022-11-28#list-repository-workflows
//
//meta:operation GET /repos/{owner}/{repo}/actions/workflows
func (s *ActionsService) ListWorkflows(ctx context.Context, owner, repo string, opts *ListOptions) (*Workflows, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/workflows", owner, repo)
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest(ctx, "GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	var workflows *Workflows
	resp, err := s.client.Do(req, &workflows)
	if err != nil {
		return nil, resp, err
	}

	return workflows, resp, nil
}

// GetWorkflowByID gets a specific workflow by ID.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflows?apiVersion=2022-11-28#get-a-workflow
//
//meta:operation GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}
func (s *ActionsService) GetWorkflowByID(ctx context.Context, owner, repo string, workflowID int64) (*Workflow, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/workflows/%v", owner, repo, workflowID)

	return s.getWorkflow(ctx, u)
}

// GetWorkflowByFileName gets a specific workflow by file name.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflows?apiVersion=2022-11-28#get-a-workflow
//
//meta:operation GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}
func (s *ActionsService) GetWorkflowByFileName(ctx context.Context, owner, repo, workflowFileName string) (*Workflow, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/workflows/%v", owner, repo, workflowFileName)

	return s.getWorkflow(ctx, u)
}

func (s *ActionsService) getWorkflow(ctx context.Context, url string) (*Workflow, *Response, error) {
	req, err := s.client.NewRequest(ctx, "GET", url, nil)
	if err != nil {
		return nil, nil, err
	}

	var workflow *Workflow
	resp, err := s.client.Do(req, &workflow)
	if err != nil {
		return nil, resp, err
	}

	return workflow, resp, nil
}

// GetWorkflowUsageByID gets a specific workflow usage by ID in the unit of billable milliseconds.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflows?apiVersion=2022-11-28#get-workflow-usage
//
//meta:operation GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing
func (s *ActionsService) GetWorkflowUsageByID(ctx context.Context, owner, repo string, workflowID int64) (*WorkflowUsage, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/workflows/%v/timing", owner, repo, workflowID)

	return s.getWorkflowUsage(ctx, u)
}

// GetWorkflowUsageByFileName gets a specific workflow usage by file name in the unit of billable milliseconds.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflows?apiVersion=2022-11-28#get-workflow-usage
//
//meta:operation GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing
func (s *ActionsService) GetWorkflowUsageByFileName(ctx context.Context, owner, repo, workflowFileName string) (*WorkflowUsage, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/workflows/%v/timing", owner, repo, workflowFileName)

	return s.getWorkflowUsage(ctx, u)
}

func (s *ActionsService) getWorkflowUsage(ctx context.Context, url string) (*WorkflowUsage, *Response, error) {
	req, err := s.client.NewRequest(ctx, "GET", url, nil)
	if err != nil {
		return nil, nil, err
	}

	var workflowUsage *WorkflowUsage
	resp, err := s.client.Do(req, &workflowUsage)
	if err != nil {
		return nil, resp, err
	}

	return workflowUsage, resp, nil
}

// CreateWorkflowDispatchEventByID manually triggers a GitHub Actions workflow run.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflows?apiVersion=2022-11-28#create-a-workflow-dispatch-event
//
//meta:operation POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches
func (s *ActionsService) CreateWorkflowDispatchEventByID(ctx context.Context, owner, repo string, workflowID int64, event CreateWorkflowDispatchEventRequest) (*WorkflowDispatchRunDetails, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/workflows/%v/dispatches", owner, repo, workflowID)

	return s.createWorkflowDispatchEvent(ctx, u, &event)
}

// CreateWorkflowDispatchEventByFileName manually triggers a GitHub Actions workflow run.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflows?apiVersion=2022-11-28#create-a-workflow-dispatch-event
//
//meta:operation POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches
func (s *ActionsService) CreateWorkflowDispatchEventByFileName(ctx context.Context, owner, repo, workflowFileName string, event CreateWorkflowDispatchEventRequest) (*WorkflowDispatchRunDetails, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/workflows/%v/dispatches", owner, repo, workflowFileName)

	return s.createWorkflowDispatchEvent(ctx, u, &event)
}

func (s *ActionsService) createWorkflowDispatchEvent(ctx context.Context, url string, event *CreateWorkflowDispatchEventRequest) (*WorkflowDispatchRunDetails, *Response, error) {
	req, err := s.client.NewRequest(ctx, "POST", url, event)
	if err != nil {
		return nil, nil, err
	}

	var dispatchRunDetails *WorkflowDispatchRunDetails
	resp, err := s.client.Do(req, &dispatchRunDetails)
	if err != nil {
		return nil, resp, err
	}

	return dispatchRunDetails, resp, nil
}

// EnableWorkflowByID enables a workflow and sets the state of the workflow to "active".
//
// GitHub API docs: https://docs.github.com/rest/actions/workflows?apiVersion=2022-11-28#enable-a-workflow
//
//meta:operation PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable
func (s *ActionsService) EnableWorkflowByID(ctx context.Context, owner, repo string, workflowID int64) (*Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/workflows/%v/enable", owner, repo, workflowID)
	return s.doNewPutRequest(ctx, u)
}

// EnableWorkflowByFileName enables a workflow and sets the state of the workflow to "active".
//
// GitHub API docs: https://docs.github.com/rest/actions/workflows?apiVersion=2022-11-28#enable-a-workflow
//
//meta:operation PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable
func (s *ActionsService) EnableWorkflowByFileName(ctx context.Context, owner, repo, workflowFileName string) (*Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/workflows/%v/enable", owner, repo, workflowFileName)
	return s.doNewPutRequest(ctx, u)
}

// DisableWorkflowByID disables a workflow and sets the state of the workflow to "disabled_manually".
//
// GitHub API docs: https://docs.github.com/rest/actions/workflows?apiVersion=2022-11-28#disable-a-workflow
//
//meta:operation PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable
func (s *ActionsService) DisableWorkflowByID(ctx context.Context, owner, repo string, workflowID int64) (*Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/workflows/%v/disable", owner, repo, workflowID)
	return s.doNewPutRequest(ctx, u)
}

// DisableWorkflowByFileName disables a workflow and sets the state of the workflow to "disabled_manually".
//
// GitHub API docs: https://docs.github.com/rest/actions/workflows?apiVersion=2022-11-28#disable-a-workflow
//
//meta:operation PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable
func (s *ActionsService) DisableWorkflowByFileName(ctx context.Context, owner, repo, workflowFileName string) (*Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/workflows/%v/disable", owner, repo, workflowFileName)
	return s.doNewPutRequest(ctx, u)
}

func (s *ActionsService) doNewPutRequest(ctx context.Context, url string) (*Response, error) {
	req, err := s.client.NewRequest(ctx, "PUT", url, nil)
	if err != nil {
		return nil, err
	}

	return s.client.Do(req, nil)
}
