package repo

import (
	"encoding/csv"
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/gitlink-org/gitlink-cli/shortcuts/common"
)

// BatchMemberShortcuts 返回批量成员管理相关的 Shortcut（由 repo.Shortcuts() 调用合并）
func BatchMemberShortcuts() []*common.Shortcut {
	return []*common.Shortcut{
		{
			Name:        "batch-invite",
			Description: "Batch invite members to a repository (from --users list or --from CSV file)",
			Flags: []common.Flag{
				{Name: "users", Usage: "Comma-separated list of user IDs to invite"},
				{Name: "from", Usage: "CSV file with user IDs (column: user_id)"},
				{Name: "dry-run", Usage: "Preview operations without executing", Bool: true},
			},
			Run: runBatchInvite,
		},
		{
			Name:        "batch-remove",
			Description: "Batch remove members from a repository (from --users list or --from CSV file)",
			Flags: []common.Flag{
				{Name: "users", Usage: "Comma-separated list of user IDs to remove"},
				{Name: "from", Usage: "CSV file with user IDs (column: user_id)"},
				{Name: "dry-run", Usage: "Preview operations without executing", Bool: true},
			},
			Run: runBatchRemove,
		},
	}
}

// runBatchInvite 执行批量邀请
func runBatchInvite(ctx *common.RuntimeContext) error {
	userIDs, err := parseUserIDs(ctx)
	if err != nil {
		return err
	}
	dryRun := ctx.Arg("dry-run") == "true"

	if err := ctx.ResolveOwnerRepo(); err != nil {
		return err
	}

	results := make([]map[string]interface{}, 0, len(userIDs))

	for _, uid := range userIDs {
		if dryRun {
			results = append(results, map[string]interface{}{
				"user_id": uid,
				"project": fmt.Sprintf("%s/%s", ctx.Owner, ctx.Repo),
				"action":  "invite",
				"status":  "would execute (dry-run)",
			})
			continue
		}

		body := map[string]interface{}{"user_id": uid}
		_, err := ctx.CallAPI("POST", ctx.RepoPath()+"/collaborators", body)
		status := "success"
		msg := ""
		if err != nil {
			status = "failed"
			msg = err.Error()
		}
		results = append(results, map[string]interface{}{
			"user_id": uid,
			"project": fmt.Sprintf("%s/%s", ctx.Owner, ctx.Repo),
			"action":  "invite",
			"status":  status,
			"message": msg,
		})
	}

	return ctx.OutputData(results)
}

// runBatchRemove 执行批量移除
func runBatchRemove(ctx *common.RuntimeContext) error {
	userIDs, err := parseUserIDs(ctx)
	if err != nil {
		return err
	}
	dryRun := ctx.Arg("dry-run") == "true"

	if err := ctx.ResolveOwnerRepo(); err != nil {
		return err
	}

	results := make([]map[string]interface{}, 0, len(userIDs))

	for _, uid := range userIDs {
		if dryRun {
			results = append(results, map[string]interface{}{
				"user_id": uid,
				"project": fmt.Sprintf("%s/%s", ctx.Owner, ctx.Repo),
				"action":  "remove",
				"status":  "would execute (dry-run)",
			})
			continue
		}

		body := map[string]interface{}{"user_id": uid}
		_, err := ctx.CallAPI("DELETE", ctx.RepoPath()+"/collaborators/remove", body)
		status := "success"
		msg := ""
		if err != nil {
			status = "failed"
			msg = err.Error()
		}
		results = append(results, map[string]interface{}{
			"user_id": uid,
			"project": fmt.Sprintf("%s/%s", ctx.Owner, ctx.Repo),
			"action":  "remove",
			"status":  status,
			"message": msg,
		})
	}

	return ctx.OutputData(results)
}

// parseUserIDs 从 --users 或 --from 参数中解析用户 ID 列表
func parseUserIDs(ctx *common.RuntimeContext) ([]int, error) {
	usersStr := ctx.Arg("users")
	csvFile := ctx.Arg("from")

	if usersStr == "" && csvFile == "" {
		return nil, fmt.Errorf("必须指定 --users（逗号分隔的用户ID）或 --from（CSV文件路径）")
	}

	var userIDs []int

	if usersStr != "" {
		for _, s := range strings.Split(usersStr, ",") {
			s = strings.TrimSpace(s)
			if s == "" {
				continue
			}
			uid, err := strconv.Atoi(s)
			if err != nil {
				return nil, fmt.Errorf("invalid user ID: %s", s)
			}
			userIDs = append(userIDs, uid)
		}
	}

	if csvFile != "" {
		f, err := os.Open(csvFile)
		if err != nil {
			return nil, fmt.Errorf("failed to open CSV file %s: %w", csvFile, err)
		}
		defer f.Close()

		reader := csv.NewReader(f)
		records, err := reader.ReadAll()
		if err != nil {
			return nil, fmt.Errorf("failed to read CSV file: %w", err)
		}

		if len(records) < 2 {
			return nil, fmt.Errorf("CSV file must have a header row and at least one data row")
		}

		// 查找 user_id 列
		header := records[0]
		colIdx := -1
		for i, h := range header {
			if strings.TrimSpace(h) == "user_id" {
				colIdx = i
				break
			}
		}
		if colIdx == -1 {
			return nil, fmt.Errorf("CSV file must have a 'user_id' column")
		}

		for _, row := range records[1:] {
			if len(row) <= colIdx {
				continue
			}
			s := strings.TrimSpace(row[colIdx])
			if s == "" {
				continue
			}
			uid, err := strconv.Atoi(s)
			if err != nil {
				return nil, fmt.Errorf("invalid user ID in CSV: %s", s)
			}
			userIDs = append(userIDs, uid)
		}
	}

	if len(userIDs) == 0 {
		return nil, fmt.Errorf("no valid user IDs found")
	}

	return userIDs, nil
}
