package entities

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

type UserRole string

const (
	RoleAdmin   UserRole = "admin"
	RoleManager UserRole = "manager"
	RoleCashier UserRole = "cashier"
	RoleWaiter  UserRole = "waiter"
)

type Permissions map[string]interface{}

func (p Permissions) Value() (driver.Value, error) {
	return json.Marshal(p)
}

func (p *Permissions) Scan(value interface{}) error {
	if value == nil {
		*p = make(Permissions)
		return nil
	}

	bytes, ok := value.([]byte)
	if !ok {
		return errors.New("type assertion to []byte failed")
	}

	return json.Unmarshal(bytes, p)
}

type User struct {
	ID           uuid.UUID    `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	Username     string       `gorm:"uniqueIndex;not null;size:100" json:"username" validate:"required,min=1,max=100"`
	Name         string       `gorm:"not null;size:255" json:"name" validate:"required,min=1,max=255"`
	Email        string       `gorm:"uniqueIndex;not null;size:255" json:"email" validate:"required,email"`
	PasswordHash string       `gorm:"not null;size:255" json:"-"`
	IsActive     bool         `gorm:"default:true" json:"is_active"`
	CreatedAt    time.Time    `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt    time.Time    `gorm:"autoUpdateTime" json:"updated_at"`
	Profile      *UserProfile `gorm:"foreignKey:UserID;references:ID" json:"profile,omitempty"`
	Departments  []Department `gorm:"many2many:user_department;foreignKey:ID;joinForeignKey:user_id;References:ID;joinReferences:department_id" json:"departments,omitempty"`
}

func (u *User) BeforeCreate(tx *gorm.DB) error {
	if u.ID == uuid.Nil {
		u.ID = uuid.New()
	}
	return nil
}

func (User) TableName() string {
	return "users"
}

func (u *User) HasPermission(permission string) bool {
	return false
}

func (u *User) CanAccessOutlet(outletID uuid.UUID) bool {

	return false
}
