package repository

import (
	"database/sql"
	"fmt"
	"strings"

	"kfz-goods-pricing/internal/database"
)

// KfzToken Token记录
type KfzToken struct {
	ID       int64
	Username string
	Token    string
	IsEnable bool
}

// TokenRepository Token仓储
type TokenRepository struct{}

// NewTokenRepository 创建Token仓储实例
func NewTokenRepository() *TokenRepository {
	return &TokenRepository{}
}

// BatchInsert 批量插入Token记录
func (r *TokenRepository) BatchInsert(tokens []string, username string) (int64, error) {
	if len(tokens) == 0 {
		return 0, nil
	}

	// 过滤空字符串
	var validTokens []string
	for _, t := range tokens {
		t := strings.TrimSpace(t)
		if t != "" {
			validTokens = append(validTokens, t)
		}
	}
	if len(validTokens) == 0 {
		return 0, nil
	}

	// 构建批量插入语句
	valuePlaceholders := make([]string, len(validTokens))
	args := make([]interface{}, 0, len(validTokens)*2)

	for i, t := range validTokens {
		valuePlaceholders[i] = "(?, ?, 1)"
		args = append(args, username, t)
	}

	query := fmt.Sprintf("INSERT INTO kfz_token (username, token, is_enable) VALUES %s", strings.Join(valuePlaceholders, ","))

	result, err := database.DB.Exec(query, args...)
	if err != nil {
		return 0, fmt.Errorf("批量插入失败: %w", err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		return 0, fmt.Errorf("获取自增ID失败: %w", err)
	}

	return id, nil
}

// Insert 插入单条Token记录
func (r *TokenRepository) Insert(username, token string, isEnable bool) (int64, error) {
	query := `INSERT INTO kfz_token (username, token, is_enable) VALUES (?, ?, ?)`

	result, err := database.DB.Exec(query, username, token, isEnable)
	if err != nil {
		return 0, fmt.Errorf("插入失败: %w", err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		return 0, fmt.Errorf("获取自增ID失败: %w", err)
	}

	return id, nil
}

// GetAll 查询所有记录
func (r *TokenRepository) GetAll() ([]*KfzToken, error) {
	query := `SELECT id, username, token, is_enable FROM kfz_token ORDER BY id ASC`

	rows, err := database.DB.Query(query)
	if err != nil {
		return nil, fmt.Errorf("查询失败: %w", err)
	}
	defer rows.Close()

	var records []*KfzToken
	for rows.Next() {
		var rec KfzToken
		err := rows.Scan(&rec.ID, &rec.Username, &rec.Token, &rec.IsEnable)
		if err != nil {
			return nil, fmt.Errorf("扫描失败: %w", err)
		}
		records = append(records, &rec)
	}

	return records, nil
}

// GetByID 根据ID查询单条记录
func (r *TokenRepository) GetByID(id int64) (*KfzToken, error) {
	query := `SELECT id, username, token, is_enable FROM kfz_token WHERE id = ?`

	row := database.DB.QueryRow(query, id)

	var rec KfzToken
	err := row.Scan(&rec.ID, &rec.Username, &rec.Token, &rec.IsEnable)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, fmt.Errorf("记录不存在")
		}
		return nil, fmt.Errorf("查询失败: %w", err)
	}

	return &rec, nil
}

// Update 更新记录
func (r *TokenRepository) Update(id int64, username, token string, isEnable bool) error {
	query := `UPDATE kfz_token SET username = ?, token = ?, is_enable = ? WHERE id = ?`

	result, err := database.DB.Exec(query, username, token, isEnable, id)
	if err != nil {
		return fmt.Errorf("更新失败: %w", err)
	}

	rowsAffected, _ := result.RowsAffected()
	if rowsAffected == 0 {
		return fmt.Errorf("记录不存在")
	}

	return nil
}

// Delete 删除记录
func (r *TokenRepository) Delete(id int64) error {
	query := `DELETE FROM kfz_token WHERE id = ?`

	result, err := database.DB.Exec(query, id)
	if err != nil {
		return fmt.Errorf("删除失败: %w", err)
	}

	rowsAffected, _ := result.RowsAffected()
	if rowsAffected == 0 {
		return fmt.Errorf("记录不存在")
	}

	return nil
}

// GetEnabledTokens 获取所有启用状态的Token
func (r *TokenRepository) GetEnabledTokens() ([]*KfzToken, error) {
	query := `SELECT id, username, token, is_enable FROM kfz_token WHERE is_enable = 1 ORDER BY id ASC`

	rows, err := database.DB.Query(query)
	if err != nil {
		return nil, fmt.Errorf("查询失败: %w", err)
	}
	defer rows.Close()

	var records []*KfzToken
	for rows.Next() {
		var rec KfzToken
		err := rows.Scan(&rec.ID, &rec.Username, &rec.Token, &rec.IsEnable)
		if err != nil {
			return nil, fmt.Errorf("扫描失败: %w", err)
		}
		records = append(records, &rec)
	}

	return records, nil
}