package entity

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

	"github.com/google/uuid"
)

// StringArray is a custom type for handling string arrays with JSON serialization
type StringArray []string

// Scan implements the sql.Scanner interface
func (s *StringArray) Scan(value interface{}) error {
	if value == nil {
		*s = StringArray{}
		return nil
	}

	switch v := value.(type) {
	case []byte:
		return json.Unmarshal(v, s)
	case string:
		return json.Unmarshal([]byte(v), s)
	default:
		return nil
	}
}

// Value implements the driver.Valuer interface
func (s StringArray) Value() (driver.Value, error) {
	if s == nil || len(s) == 0 {
		return "[]", nil
	}
	return json.Marshal(s)
}

type ClientApprovalSettings struct {
	ID                       uint      `json:"id" gorm:"primaryKey;type:int4;autoIncrement"`
	ClientId                 uuid.UUID `json:"client_id" gorm:"type:UUID;not null;uniqueIndex"`
	RequiresApproval         *bool     `json:"requires_approval" gorm:"type:bool;default:true"`      // false = no approval needed
	DefaultWorkflowId        *uint     `json:"default_workflow_id" gorm:"type:int4"`                 // default workflow for this client
	AutoPublishArticles      *bool     `json:"auto_publish_articles" gorm:"type:bool;default:false"` // auto publish after creation
	ApprovalExemptUsers      []uint    `json:"approval_exempt_users" gorm:"type:int4[]"`             // user IDs exempt from approval
	ApprovalExemptRoles      []uint    `json:"approval_exempt_roles" gorm:"type:int4[]"`             // role IDs exempt from approval
	ApprovalExemptCategories []uint    `json:"approval_exempt_categories" gorm:"type:int4[]"`        // category IDs exempt from approval
	RequireApprovalFor       []string  `json:"require_approval_for" gorm:"type:jsonb"`               // specific content types that need approval
	SkipApprovalFor          []string  `json:"skip_approval_for" gorm:"type:jsonb"`                  // specific content types that skip approval
	IsActive                 *bool     `json:"is_active" gorm:"type:bool;default:true"`
	CreatedAt                time.Time `json:"created_at" gorm:"default:now()"`
	UpdatedAt                time.Time `json:"updated_at" gorm:"default:now()"`

	// Relations
	Client   Clients            `json:"client" gorm:"foreignKey:ClientId;constraint:OnDelete:CASCADE"`
	Workflow *ApprovalWorkflows `json:"workflow" gorm:"foreignKey:DefaultWorkflowId"`
}
