package models

import (
	"time"

	"golang.org/x/crypto/bcrypt"
)

// AdminRole represents the role of an admin user
type AdminRole string

const (
	AdminRoleAdmin      AdminRole = "admin"
	AdminRoleSuperAdmin AdminRole = "super_admin"
)

// AdminUser represents an administrator for the admin panel
type AdminUser struct {
	ID        uint       `gorm:"primaryKey" json:"id"`
	Email     string     `gorm:"uniqueIndex;size:254;not null" json:"email"`
	Password  string     `gorm:"size:128;not null" json:"-"`
	FirstName string     `gorm:"size:100" json:"first_name"`
	LastName  string     `gorm:"size:100" json:"last_name"`
	Role      AdminRole  `gorm:"size:20;default:'admin'" json:"role"`
	IsActive  bool       `gorm:"default:true" json:"is_active"`
	LastLogin *time.Time `json:"last_login,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
}

// TableName specifies the table name for AdminUser
func (AdminUser) TableName() string {
	return "admin_users"
}

// SetPassword hashes and sets the password
func (a *AdminUser) SetPassword(password string) error {
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	a.Password = string(hash)
	return nil
}

// CheckPassword verifies the password against the stored hash
func (a *AdminUser) CheckPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(a.Password), []byte(password))
	return err == nil
}

// FullName returns the admin's full name
func (a *AdminUser) FullName() string {
	if a.FirstName == "" && a.LastName == "" {
		return a.Email
	}
	return a.FirstName + " " + a.LastName
}

// IsSuperAdmin checks if the admin has super admin privileges
func (a *AdminUser) IsSuperAdmin() bool {
	return a.Role == AdminRoleSuperAdmin
}
