package user

import (
	"time"

	"gorm.io/gorm"

	filemanager "wucher/internal/domain/file_manager"
	"wucher/internal/shared/pkg/uuidv7"
)

// User maps to the "users" table (shared with auth).
type User struct {
	ID                  []byte        `gorm:"type:binary(16);primaryKey;column:id"`
	RoleID              []byte        `gorm:"type:binary(16);index;not null;column:role_id"`
	RoleIDs             [][]byte      `gorm:"-"`
	ImageAttachmentID   []byte        `gorm:"type:binary(16);index;column:image_attachment_id"`
	ProfileAttachmentID []byte        `gorm:"type:binary(16);index;column:profile_attachment_id"`
	Email               string        `gorm:"type:varchar(191);uniqueIndex;not null;column:email"`
	SSOEmail            *string       `gorm:"type:varchar(191);uniqueIndex;column:sso_email"`
	Username            string        `gorm:"type:varchar(100);index;column:username"`
	FirstName           string        `gorm:"type:varchar(100);not null;column:first_name"`
	LastName            string        `gorm:"type:varchar(100);not null;column:last_name"`
	MobilePhone         string        `gorm:"type:varchar(32);index;column:mobile_phone"`
	Timezone            string        `gorm:"type:varchar(64);not null;default:UTC;column:timezone"`
	Roles               []RoleSummary `gorm:"-"`
	RoleName            string        `gorm:"->;column:role_name"`
	RoleDescription     string        `gorm:"->;column:role_description"`
	EmailVerifiedAt     *time.Time    `gorm:"column:email_verified_at"`
	IsActive            bool          `gorm:"not null;default:true;column:is_active"`

	ImageAttachment           *filemanager.Attachment `gorm:"foreignKey:ImageAttachmentID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:SET NULL"`
	ProfileAttachment         *filemanager.Attachment `gorm:"foreignKey:ProfileAttachmentID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:SET NULL"`
	ProfileAttachmentPatchSet bool                    `gorm:"-"`

	CreatedAt time.Time
	CreatedBy []byte `gorm:"type:binary(16);column:created_by"`
	UpdatedAt time.Time
	UpdatedBy []byte `gorm:"type:binary(16);column:updated_by"`
}

type RoleSummary struct {
	ID          []byte `gorm:"column:id"`
	Name        string `gorm:"column:name"`
	Description string `gorm:"column:description"`
}

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

func (u *User) BeforeCreate(tx *gorm.DB) error {
	if len(u.ID) == 0 {
		u.ID = uuidv7.MustBytes()
	}
	return nil
}
