package repository

import (
	"gorm.io/gorm"
	"hyapp-admin-server/internal/config"
	"hyapp-admin-server/internal/model"
)

type Store struct {
	db *gorm.DB
}

type ListOptions struct {
	Page     int
	PageSize int
	Keyword  string
	Role     string
	Status   string
	TeamID   uint
	TeamIDs  []uint
	Sort     string
}

type SearchResult struct {
	Type     string `json:"type"`
	ID       string `json:"id"`
	Title    string `json:"title"`
	Subtitle string `json:"subtitle"`
	Target   string `json:"target"`
}

type DashboardOverview struct {
	UsersTotal    int              `json:"usersTotal"`
	ActiveUsers   int              `json:"activeUsers"`
	LockedUsers   int              `json:"lockedUsers"`
	DisabledUsers int              `json:"disabledUsers"`
	RolesTotal    int              `json:"rolesTotal"`
	MenuTotal     int              `json:"menuTotal"`
	LogsToday     int              `json:"logsToday"`
	Series        map[string][]int `json:"series"`
	UpdatedAtMS   int64            `json:"updatedAtMs"`
}

type MenuSortItem struct {
	ID   uint `json:"id"`
	Sort int  `json:"sort"`
}

type DataAccess struct {
	UserID     uint
	All        bool
	Restricted bool
	SelfOnly   bool
	Teams      []string
}

func New(db *gorm.DB) *Store {
	return &Store{db: db}
}

func (s *Store) AutoMigrate() error {
	return s.db.AutoMigrate(
		&model.Team{},
		&model.User{},
		&model.Role{},
		&model.Permission{},
		&model.Menu{},
		&model.AppConfig{},
		&model.AppBanner{},
		&model.AppSplashScreen{},
		&model.AppPopup{},
		&model.AppVersion{},
		&model.AppExploreTab{},
		&model.HostAgencySalaryPolicy{},
		&model.HostAgencySalaryPolicyRegion{},
		&model.HostAgencySalaryPolicyActiveScope{},
		&model.HostAgencySalaryLevel{},
		&model.PolicyTemplate{},
		&model.PolicyTemplateVersion{},
		&model.PolicyInstance{},
		&model.PolicyPublishJob{},
		&model.PolicyPublishItem{},
		&model.TeamSalaryPolicy{},
		&model.TeamSalaryLevel{},
		&model.RefreshToken{},
		&model.LoginLog{},
		&model.OperationLog{},
		&model.DataScope{},
		&model.UserAppScope{},
		&model.UserMoneyScope{},
		&model.TemporaryPaymentLinkOwner{},
		&model.LegacyGooglePaidDetail{},
		&model.LegacyGooglePaidSyncAttempt{},
		&model.CoinSellerRechargeOrder{},
		&model.UserWithdrawalApplication{},
		&model.AdminJob{},
		&model.ExternalAdminAccount{},
		&model.ExternalAdminSession{},
		&model.ExternalAdminLoginLog{},
		&model.ExternalAdminOperationLog{},
	)
}

func (s *Store) Ping() error {
	sqlDB, err := s.db.DB()
	if err != nil {
		return err
	}

	return sqlDB.Ping()
}

func (s *Store) Seed(cfg config.Config) error {
	if !cfg.Bootstrap.Enabled {
		return nil
	}
	if err := s.seedPermissions(); err != nil {
		return err
	}
	if err := s.seedMenus(); err != nil {
		return err
	}
	if err := s.seedTeams(); err != nil {
		return err
	}
	if err := s.pruneDeprecatedDefaults(); err != nil {
		return err
	}
	if err := s.seedRoles(); err != nil {
		return err
	}
	if err := s.seedUsers(cfg); err != nil {
		return err
	}
	return nil
}
