package filemanager

import (
	"strings"
	"time"

	"gorm.io/gorm"

	"wucher/internal/shared/pkg/uuidv7"
)

const (
	FileUploadIntentStatusPending   = "pending"
	FileUploadIntentStatusCompleted = "completed"
	FileUploadIntentStatusExpired   = "expired"
)

type FileUploadIntent struct {
	ID             []byte     `gorm:"type:binary(16);primaryKey;column:id"`
	Name           string     `gorm:"type:varchar(255);not null;column:name"`
	NameNormalized string     `gorm:"type:varchar(255);not null;column:name_normalized"`
	Extension      string     `gorm:"type:varchar(32);column:extension"`
	SizeBytes      int64      `gorm:"type:bigint unsigned;not null;default:0;column:size_bytes"`
	MimeType       string     `gorm:"type:varchar(255);not null;column:mime_type"`
	Bucket         string     `gorm:"type:varchar(128);not null;column:bucket"`
	ObjectKey      string     `gorm:"type:varchar(512);not null;uniqueIndex:uq_file_upload_intents_object_key"`
	Status         string     `gorm:"type:varchar(32);index;not null;default:'pending';column:status"`
	ExpiresAt      time.Time  `gorm:"index;not null;column:expires_at"`
	CompletedAt    *time.Time `gorm:"column:completed_at"`
	CreatedAt      time.Time  `gorm:"column:created_at"`
	CreatedBy      []byte     `gorm:"type:binary(16);column:created_by"`
	UpdatedAt      time.Time  `gorm:"column:updated_at"`
	UpdatedBy      []byte     `gorm:"type:binary(16);column:updated_by"`
}

func (FileUploadIntent) TableName() string {
	return "file_upload_intents"
}

func (m *FileUploadIntent) BeforeCreate(_ *gorm.DB) error {
	if len(m.ID) == 0 {
		m.ID = uuidv7.MustBytes()
	}
	if strings.TrimSpace(m.Status) == "" {
		m.Status = FileUploadIntentStatusPending
	}
	return nil
}

func NormalizeFileUploadIntentStatus(status string) string {
	return strings.ToLower(strings.TrimSpace(status))
}
