package domain

import (
	"time"

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

const (
	WorksmobileOutboxStatusPending    = "pending"
	WorksmobileOutboxStatusProcessing = "processing"
	WorksmobileOutboxStatusProcessed  = "processed"
	WorksmobileOutboxStatusFailed     = "failed"
)

const (
	WorksmobileResourceOrgUnit = "ORGUNIT"
	WorksmobileResourceUser    = "USER"
)

const (
	WorksmobileActionUpsert  = "UPSERT"
	WorksmobileActionDelete  = "DELETE"
	WorksmobileActionDryRun  = "DRY_RUN"
	WorksmobileActionSuspend = "SUSPEND"
)

type WorksmobileOutbox struct {
	ID            string     `gorm:"primaryKey;type:uuid;default:gen_random_uuid()" json:"id"`
	ResourceType  string     `gorm:"not null;index:idx_worksmobile_outbox_resource" json:"resourceType"`
	ResourceID    string     `gorm:"not null;index:idx_worksmobile_outbox_resource" json:"resourceId"`
	Action        string     `gorm:"not null" json:"action"`
	Payload       JSONMap    `gorm:"type:jsonb" json:"payload,omitempty"`
	DedupeKey     string     `gorm:"uniqueIndex" json:"dedupeKey"`
	Status        string     `gorm:"default:'pending';index" json:"status"`
	RetryCount    int        `gorm:"default:0" json:"retryCount"`
	LastError     string     `json:"lastError,omitempty"`
	NextAttemptAt *time.Time `json:"nextAttemptAt,omitempty"`
	ProcessedAt   *time.Time `json:"processedAt,omitempty"`
	CreatedAt     time.Time  `json:"createdAt"`
	UpdatedAt     time.Time  `json:"updatedAt"`
}

func (w *WorksmobileOutbox) BeforeCreate(tx *gorm.DB) error {
	if w.ID == "" {
		w.ID = uuid.NewString()
	}
	if w.Status == "" {
		w.Status = WorksmobileOutboxStatusPending
	}
	return nil
}

type WorksmobileResourceMapping struct {
	ID                    string     `gorm:"primaryKey;type:uuid;default:gen_random_uuid()" json:"id"`
	BaronResourceType     string     `gorm:"not null;uniqueIndex:idx_worksmobile_mapping_baron" json:"baronResourceType"`
	BaronResourceID       string     `gorm:"not null;uniqueIndex:idx_worksmobile_mapping_baron" json:"baronResourceId"`
	ExternalKey           string     `gorm:"not null;uniqueIndex" json:"externalKey"`
	WorksmobileResourceID string     `json:"worksmobileResourceId,omitempty"`
	DomainID              int64      `json:"domainId"`
	LastSyncedAt          *time.Time `json:"lastSyncedAt,omitempty"`
	CreatedAt             time.Time  `json:"createdAt"`
	UpdatedAt             time.Time  `json:"updatedAt"`
}

func (w *WorksmobileResourceMapping) BeforeCreate(tx *gorm.DB) error {
	if w.ID == "" {
		w.ID = uuid.NewString()
	}
	return nil
}
