// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package issues

import (
	stdctx "context"
	"errors"
	"time"

	gitea "gitea.dev/sdk"

	"gitea.dev/tea/cmd/flags"
	"gitea.dev/tea/modules/context"
	"gitea.dev/tea/modules/print"
	"github.com/araddon/dateparse"
	"github.com/urfave/cli/v3"
)

var issueFieldsFlag = flags.FieldsFlag(print.IssueFields, []string{
	"index", "title", "state", "author", "milestone", "labels", "owner", "repo",
})

// CmdIssuesList represents a sub command of issues to list issues
var CmdIssuesList = cli.Command{
	Name:        "list",
	Aliases:     []string{"ls"},
	Usage:       "List issues of the repository",
	Description: `List issues of the repository`,
	ArgsUsage:   " ", // command does not accept arguments
	Action:      RunIssuesList,
	Flags:       append([]cli.Flag{issueFieldsFlag}, flags.IssueListingFlags...),
}

// RunIssuesList list issues
func RunIssuesList(requestCtx stdctx.Context, cmd *cli.Command) error {
	ctx, err := context.InitCommand(cmd)
	if err != nil {
		return err
	}

	state, err := flags.ParseState(ctx.String("state"))
	if err != nil {
		return err
	}

	kind, err := flags.ParseIssueKind(ctx.String("kind"), gitea.IssueTypeIssue)
	if err != nil {
		return err
	}

	var from, until time.Time
	if ctx.IsSet("from") {
		from, err = dateparse.ParseLocal(ctx.String("from"))
		if err != nil {
			return err
		}
	}
	if ctx.IsSet("until") {
		until, err = dateparse.ParseLocal(ctx.String("until"))
		if err != nil {
			return err
		}
	}
	owner := ctx.Owner
	if ctx.IsSet("owner") {
		owner = ctx.String("owner")
	}

	// ignore error, as we don't do any input validation on these flags
	labels, _ := flags.LabelFilterFlag.GetValues(cmd)
	milestones, _ := flags.MilestoneFilterFlag.GetValues(cmd)
	var issues []*gitea.Issue
	if ctx.Repo != "" {
		issues, _, err = ctx.Login.Client().Issues.ListRepoIssues(requestCtx, owner, ctx.Repo, gitea.ListIssueOption{
			ListOptions: flags.GetListOptions(cmd),
			State:       state,
			Type:        kind,
			KeyWord:     ctx.String("keyword"),
			CreatedBy:   ctx.String("author"),
			AssignedBy:  ctx.String("assignee"),
			MentionedBy: ctx.String("mentions"),
			Labels:      labels,
			Milestones:  milestones,
			Since:       from,
			Before:      until,
		})
		if err != nil {
			return err
		}
	} else {
		if ctx.IsSet("assignee") {
			return errors.New("--assignee requires --repo (global issue search does not support assignee filter)")
		}
		issues, _, err = ctx.Login.Client().Issues.ListIssues(requestCtx, gitea.ListIssueOption{
			ListOptions: flags.GetListOptions(cmd),
			State:       state,
			Type:        kind,
			KeyWord:     ctx.String("keyword"),
			CreatedBy:   ctx.String("author"),
			MentionedBy: ctx.String("mentions"),
			Labels:      labels,
			Milestones:  milestones,
			Since:       from,
			Before:      until,
			Owner:       owner,
		})
		if err != nil {
			return err
		}
	}

	fields, err := issueFieldsFlag.GetValues(cmd)
	if err != nil {
		return err
	}

	return print.IssuesPullsList(issues, ctx.Output, fields)
}
