// Copyright 2026 The MokoGitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package repo

import (
	"errors"
	"fmt"
	"net/http"
	"reflect"

	issues_model "code.mokoconsulting.tech/MokoConsulting/MokoGitea/models/issues"
	api "code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/structs"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/web"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/services/context"
	issue_service "code.mokoconsulting.tech/MokoConsulting/MokoGitea/services/issue"
)

// BulkSetIssueLabels adds, removes, or replaces labels on multiple issues
func BulkSetIssueLabels(ctx *context.APIContext) {
	// swagger:operation POST /repos/{owner}/{repo}/issues/bulk/labels issue issueBulkSetLabels
	// ---
	// summary: Add, remove, or replace labels on multiple issues
	// consumes:
	// - application/json
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// - name: body
	//   in: body
	//   schema:
	//     "$ref": "#/definitions/IssueBulkLabelsOption"
	// responses:
	//   "200":
	//     "$ref": "#/responses/IssueBulkResult"
	//   "403":
	//     "$ref": "#/responses/forbidden"
	//   "404":
	//     "$ref": "#/responses/notFound"
	//   "422":
	//     "$ref": "#/responses/validationError"

	form := web.GetForm(ctx).(*api.IssueBulkLabelsOption)
	if len(form.Issues) == 0 {
		ctx.APIError(http.StatusUnprocessableEntity, errors.New("issues list must not be empty"))
		return
	}

	action := form.Action
	if action == "" {
		action = "add"
	}
	if action != "add" && action != "remove" && action != "replace" {
		ctx.APIError(http.StatusUnprocessableEntity, fmt.Errorf("invalid action %q: must be add, remove, or replace", action))
		return
	}

	labels, err := resolveBulkLabels(ctx, form.Labels)
	if err != nil {
		return // error already written to ctx
	}

	result := api.IssueBulkResult{Failures: make(map[int64]string)}

	for _, index := range form.Issues {
		issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, index)
		if err != nil {
			if issues_model.IsErrIssueNotExist(err) {
				result.Failures[index] = "issue not found"
			} else {
				result.Failures[index] = err.Error()
			}
			result.FailureCount++
			continue
		}

		if !ctx.Repo.Permission.CanWriteIssuesOrPulls(issue.IsPull) {
			result.Failures[index] = "no write permission"
			result.FailureCount++
			continue
		}

		switch action {
		case "add":
			err = issue_service.AddLabels(ctx, issue, ctx.Doer, labels)
		case "remove":
			for _, label := range labels {
				if err = issue_service.RemoveLabel(ctx, issue, ctx.Doer, label); err != nil {
					break
				}
			}
		case "replace":
			err = issue_service.ReplaceLabels(ctx, issue, ctx.Doer, labels)
		}

		if err != nil {
			result.Failures[index] = err.Error()
			result.FailureCount++
			continue
		}
		result.SuccessCount++
	}

	ctx.JSON(http.StatusOK, result)
}

// BulkSetIssueState closes or reopens multiple issues
func BulkSetIssueState(ctx *context.APIContext) {
	// swagger:operation POST /repos/{owner}/{repo}/issues/bulk/state issue issueBulkSetState
	// ---
	// summary: Close or reopen multiple issues
	// consumes:
	// - application/json
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// - name: body
	//   in: body
	//   schema:
	//     "$ref": "#/definitions/IssueBulkStateOption"
	// responses:
	//   "200":
	//     "$ref": "#/responses/IssueBulkResult"
	//   "403":
	//     "$ref": "#/responses/forbidden"
	//   "422":
	//     "$ref": "#/responses/validationError"

	form := web.GetForm(ctx).(*api.IssueBulkStateOption)
	if len(form.Issues) == 0 {
		ctx.APIError(http.StatusUnprocessableEntity, errors.New("issues list must not be empty"))
		return
	}
	if form.State != "open" && form.State != "closed" {
		ctx.APIError(http.StatusUnprocessableEntity, fmt.Errorf("invalid state %q: must be open or closed", form.State))
		return
	}

	result := api.IssueBulkResult{Failures: make(map[int64]string)}

	for _, index := range form.Issues {
		issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, index)
		if err != nil {
			if issues_model.IsErrIssueNotExist(err) {
				result.Failures[index] = "issue not found"
			} else {
				result.Failures[index] = err.Error()
			}
			result.FailureCount++
			continue
		}

		if !ctx.Repo.Permission.CanWriteIssuesOrPulls(issue.IsPull) {
			result.Failures[index] = "no write permission"
			result.FailureCount++
			continue
		}

		if err := issue.LoadRepo(ctx); err != nil {
			result.Failures[index] = err.Error()
			result.FailureCount++
			continue
		}

		if form.State == "closed" && !issue.IsClosed {
			if err := issue_service.CloseIssue(ctx, issue, ctx.Doer, ""); err != nil {
				result.Failures[index] = err.Error()
				result.FailureCount++
				continue
			}
		} else if form.State == "open" && issue.IsClosed {
			if err := issue_service.ReopenIssue(ctx, issue, ctx.Doer, ""); err != nil {
				result.Failures[index] = err.Error()
				result.FailureCount++
				continue
			}
		}
		result.SuccessCount++
	}

	ctx.JSON(http.StatusOK, result)
}

// BulkSetIssueMilestone assigns a milestone to multiple issues
func BulkSetIssueMilestone(ctx *context.APIContext) {
	// swagger:operation POST /repos/{owner}/{repo}/issues/bulk/milestone issue issueBulkSetMilestone
	// ---
	// summary: Assign a milestone to multiple issues
	// consumes:
	// - application/json
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// - name: body
	//   in: body
	//   schema:
	//     "$ref": "#/definitions/IssueBulkMilestoneOption"
	// responses:
	//   "200":
	//     "$ref": "#/responses/IssueBulkResult"
	//   "403":
	//     "$ref": "#/responses/forbidden"
	//   "422":
	//     "$ref": "#/responses/validationError"

	form := web.GetForm(ctx).(*api.IssueBulkMilestoneOption)
	if len(form.Issues) == 0 {
		ctx.APIError(http.StatusUnprocessableEntity, errors.New("issues list must not be empty"))
		return
	}

	// Validate milestone exists if non-zero
	if form.MilestoneID > 0 {
		has, err := issues_model.HasMilestoneByRepoID(ctx, ctx.Repo.Repository.ID, form.MilestoneID)
		if err != nil {
			ctx.APIErrorInternal(err)
			return
		}
		if !has {
			ctx.APIErrorNotFound("milestone not found")
			return
		}
	}

	result := api.IssueBulkResult{Failures: make(map[int64]string)}

	for _, index := range form.Issues {
		issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, index)
		if err != nil {
			if issues_model.IsErrIssueNotExist(err) {
				result.Failures[index] = "issue not found"
			} else {
				result.Failures[index] = err.Error()
			}
			result.FailureCount++
			continue
		}

		if !ctx.Repo.Permission.CanWriteIssuesOrPulls(issue.IsPull) {
			result.Failures[index] = "no write permission"
			result.FailureCount++
			continue
		}

		oldMilestoneID := issue.MilestoneID
		issue.MilestoneID = form.MilestoneID

		if err := issue_service.ChangeMilestoneAssign(ctx, issue, ctx.Doer, oldMilestoneID); err != nil {
			result.Failures[index] = err.Error()
			result.FailureCount++
			continue
		}
		result.SuccessCount++
	}

	ctx.JSON(http.StatusOK, result)
}

// BulkSetIssueAssignees sets assignees on multiple issues
func BulkSetIssueAssignees(ctx *context.APIContext) {
	// swagger:operation POST /repos/{owner}/{repo}/issues/bulk/assignees issue issueBulkSetAssignees
	// ---
	// summary: Set assignees on multiple issues
	// consumes:
	// - application/json
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// - name: body
	//   in: body
	//   schema:
	//     "$ref": "#/definitions/IssueBulkAssigneesOption"
	// responses:
	//   "200":
	//     "$ref": "#/responses/IssueBulkResult"
	//   "403":
	//     "$ref": "#/responses/forbidden"
	//   "422":
	//     "$ref": "#/responses/validationError"

	form := web.GetForm(ctx).(*api.IssueBulkAssigneesOption)
	if len(form.Issues) == 0 {
		ctx.APIError(http.StatusUnprocessableEntity, errors.New("issues list must not be empty"))
		return
	}

	result := api.IssueBulkResult{Failures: make(map[int64]string)}

	for _, index := range form.Issues {
		issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, index)
		if err != nil {
			if issues_model.IsErrIssueNotExist(err) {
				result.Failures[index] = "issue not found"
			} else {
				result.Failures[index] = err.Error()
			}
			result.FailureCount++
			continue
		}

		if !ctx.Repo.Permission.CanWriteIssuesOrPulls(issue.IsPull) {
			result.Failures[index] = "no write permission"
			result.FailureCount++
			continue
		}

		if err := issue.LoadRepo(ctx); err != nil {
			result.Failures[index] = err.Error()
			result.FailureCount++
			continue
		}

		if err := issue.LoadAssignees(ctx); err != nil {
			result.Failures[index] = err.Error()
			result.FailureCount++
			continue
		}

		if err := issue_service.UpdateAssignees(ctx, issue, "", form.Assignees, ctx.Doer); err != nil {
			result.Failures[index] = err.Error()
			result.FailureCount++
			continue
		}
		result.SuccessCount++
	}

	ctx.JSON(http.StatusOK, result)
}

// resolveBulkLabels resolves label IDs or names into label models
func resolveBulkLabels(ctx *context.APIContext, rawLabels []any) ([]*issues_model.Label, error) {
	var (
		labelIDs   []int64
		labelNames []string
	)
	for _, label := range rawLabels {
		rv := reflect.ValueOf(label)
		switch rv.Kind() {
		case reflect.Float64:
			labelIDs = append(labelIDs, int64(rv.Float()))
		case reflect.String:
			labelNames = append(labelNames, rv.String())
		default:
			ctx.APIError(http.StatusBadRequest, errors.New("a label must be an integer or a string"))
			return nil, errors.New("invalid label")
		}
	}
	if len(labelIDs) > 0 && len(labelNames) > 0 {
		ctx.APIError(http.StatusBadRequest, errors.New("labels should be an array of strings or integers, not both"))
		return nil, errors.New("invalid labels")
	}
	if len(labelNames) > 0 {
		repoLabelIDs, err := issues_model.GetLabelIDsInRepoByNames(ctx, ctx.Repo.Repository.ID, labelNames)
		if err != nil {
			ctx.APIErrorInternal(err)
			return nil, err
		}
		labelIDs = append(labelIDs, repoLabelIDs...)
		if ctx.Repo.Owner.IsOrganization() {
			orgLabelIDs, err := issues_model.GetLabelIDsInOrgByNames(ctx, ctx.Repo.Owner.ID, labelNames)
			if err != nil {
				ctx.APIErrorInternal(err)
				return nil, err
			}
			labelIDs = append(labelIDs, orgLabelIDs...)
		}
	}

	labels, err := issues_model.GetLabelsByIDs(ctx, labelIDs, "id", "repo_id", "org_id", "name", "exclusive")
	if err != nil {
		ctx.APIErrorInternal(err)
		return nil, err
	}

	return labels, nil
}
