package service

import (
	"fmt"
	"verification-platform-backend/internal/database"
	"verification-platform-backend/internal/model"
)

type PackageFeature string

const (
	FeatureCloudData   PackageFeature = "cloud_data"
	FeatureDynamicCode PackageFeature = "dynamic_code"
	FeatureEmail       PackageFeature = "email"
	FeatureExtension   PackageFeature = "extension"
	FeatureAgent       PackageFeature = "agent"
)

func GetUserPackagePermission(userID uint) (*model.PackagePermission, error) {
	var user model.User
	if err := database.DB.First(&user, userID).Error; err != nil {
		return nil, err
	}

	if user.CurrentPackageID == nil {
		return nil, fmt.Errorf("用户没有当前套餐")
	}

	var userPackage model.UserPackage
	if err := database.DB.Where("user_id = ? AND package_id = ? AND status = ?", userID, *user.CurrentPackageID, "active").First(&userPackage).Error; err != nil {
		return nil, fmt.Errorf("用户套餐已过期或无效")
	}

	var permission model.PackagePermission
	if err := database.DB.Where("package_id = ?", *user.CurrentPackageID).First(&permission).Error; err != nil {
		return nil, err
	}

	return &permission, nil
}

func CheckPackageFeature(userID uint, feature PackageFeature) (bool, error) {
	permission, err := GetUserPackagePermission(userID)
	if err != nil {
		return false, err
	}

	switch feature {
	case FeatureCloudData:
		return permission.AllowCloudData, nil
	case FeatureDynamicCode:
		return permission.AllowDynamicCode, nil
	case FeatureEmail:
		return permission.AllowEmail, nil
	case FeatureExtension:
		return permission.AllowExtension, nil
	case FeatureAgent:
		return permission.AllowAgent, nil
	default:
		return false, fmt.Errorf("未知的功能: %s", feature)
	}
}

func GetApplicationDisabledStatus(appID uint) bool {
	return false
}

type ApplicationWithStatus struct {
	ID                  uint   `json:"id"`
	UserID                 uint   `json:"user_id"`
	Name                   string `json:"name"`
	Description            string `json:"description"`
	AppKey                 string `json:"app_key"`
	IconURL                string `json:"icon_url"`
	Status                 string `json:"status"`
	BillingType            string `json:"billing_type"`
	LoginPolicy            string `json:"login_policy"`
	MaxDevices             int    `json:"max_devices"`
	MultiOpenMode          string `json:"multi_open_mode"`
	EnableTrial            bool   `json:"enable_trial"`
	TrialDays              int    `json:"trial_days"`
	EnableFreePeriod       bool   `json:"enable_free_period"`
	FreePeriodType         string `json:"free_period_type"`
	FreePeriodStart        string `json:"free_period_start"`
	FreePeriodEnd          string `json:"free_period_end"`
	FreePeriodWeekdays     string `json:"free_period_weekdays"`
	FreePeriodStartTime    string `json:"free_period_start_time"`
	FreePeriodEndTime      string `json:"free_period_end_time"`
	HeartbeatInterval      int    `json:"heartbeat_interval"`
	HeartbeatTimeout       int    `json:"heartbeat_timeout"`
	MaxAttempts            int    `json:"max_attempts"`
	LockDuration           int    `json:"lock_duration"`
	DeductionMode          string `json:"deduction_mode"`
	DeductionType          string `json:"deduction_type"`
	DeductionInterval      int    `json:"deduction_interval"`
	DeductionUnit          string `json:"deduction_unit"`
	DeductionAmount        float64 `json:"deduction_amount"`
	AllowRegister          bool   `json:"allow_register"`
	EnableLoginVerify      bool   `json:"enable_login_verify"`
	EnableRegisterVerify   bool   `json:"enable_register_verify"`
	VerifyMethod           string `json:"verify_method"`
	EnablePasswordReset    bool   `json:"enable_password_reset"`
	PasswordResetMethod    string `json:"password_reset_method"`
	PasswordResetEmailID   *uint  `json:"password_reset_email_id"`
	PasswordResetSmsID     *uint  `json:"password_reset_sms_id"`
	CreatedAt              string `json:"created_at"`
	UpdatedAt              string `json:"updated_at"`
	DisabledByPackage      bool   `json:"disabled_by_package"`
}

func GetApplicationsWithDisabledStatus(userID uint) ([]ApplicationWithStatus, error) {
	var user model.User
	if err := database.DB.First(&user, userID).Error; err != nil {
		return nil, err
	}

	var apps []model.Application
	if err := database.DB.Where("user_id = ?", userID).Order("created_at ASC").Find(&apps).Error; err != nil {
		return nil, err
	}

	result := make([]ApplicationWithStatus, len(apps))
	for i, app := range apps {
		result[i] = ApplicationWithStatus{
			ID:                  app.ID,
			UserID:              app.UserID,
			Name:                app.Name,
			Description:         app.Description,
			AppKey:              app.AppKey,
			IconURL:             app.IconURL,
			Status:              app.Status,
			BillingType:         app.BillingType,
			LoginPolicy:         app.LoginPolicy,
			MaxDevices:          app.MaxDevices,
			MultiOpenMode:       app.MultiOpenMode,
			EnableTrial:         app.EnableTrial,
			TrialDays:           app.TrialDays,
			EnableFreePeriod:    app.EnableFreePeriod,
			FreePeriodType:      app.FreePeriodType,
			FreePeriodStart:     app.FreePeriodStart,
			FreePeriodEnd:       app.FreePeriodEnd,
			FreePeriodWeekdays:  app.FreePeriodWeekdays,
			FreePeriodStartTime: app.FreePeriodStartTime,
			FreePeriodEndTime:   app.FreePeriodEndTime,
			HeartbeatInterval:   app.HeartbeatInterval,
			HeartbeatTimeout:    app.HeartbeatTimeout,
			MaxAttempts:         app.MaxAttempts,
			LockDuration:        app.LockDuration,
			DeductionMode:       app.DeductionMode,
			DeductionType:       app.DeductionType,
			DeductionInterval:   app.DeductionInterval,
			DeductionUnit:       app.DeductionUnit,
			DeductionAmount:     app.DeductionAmount,
			AllowRegister:       app.AllowRegister,
			EnableLoginVerify:   app.EnableLoginVerify,
			EnableRegisterVerify: app.EnableRegisterVerify,
			VerifyMethod:        app.VerifyMethod,
			EnablePasswordReset: app.EnablePasswordReset,
			PasswordResetMethod: app.PasswordResetMethod,
			PasswordResetEmailID: app.PasswordResetEmailID,
			PasswordResetSmsID:  app.PasswordResetSmsID,
			CreatedAt:           app.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
			UpdatedAt:           app.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
		}
	}

	if user.CurrentPackageID == nil {
		for i := range result {
			result[i].DisabledByPackage = true
		}
		return result, nil
	}

	var userPackage model.UserPackage
	if err := database.DB.Where("user_id = ? AND package_id = ? AND status = ?", userID, *user.CurrentPackageID, "active").First(&userPackage).Error; err != nil {
		for i := range result {
			result[i].DisabledByPackage = true
		}
		return result, nil
	}

	var permission model.PackagePermission
	if err := database.DB.Where("package_id = ?", *user.CurrentPackageID).First(&permission).Error; err != nil {
		return result, nil
	}

	if permission.MaxApplications <= 0 {
		return result, nil
	}

	for i := range result {
		result[i].DisabledByPackage = i >= permission.MaxApplications
	}

	return result, nil
}
