package models

import (
	"time"

	"github.com/google/uuid"
)

type Ticket struct {
	ID           uuid.UUID  `gorm:"type:uuid;default:gen_random_uuid();primaryKey" json:"id"`
	UserID       uuid.UUID  `gorm:"type:uuid;not null;index" json:"user_id"`
	AssignedTo   *uuid.UUID `gorm:"type:uuid" json:"assigned_to,omitempty"`
	Category     string     `gorm:"type:varchar(32);not null" json:"category"`
	Priority     int        `gorm:"type:smallint;not null" json:"priority"`
	Status       string     `gorm:"type:varchar(32);not null" json:"status"`
	Subject      string     `gorm:"type:varchar(255);not null" json:"subject"`
	RelatedMatch *uuid.UUID `gorm:"type:uuid" json:"related_match,omitempty"`
	RelatedBan   *uuid.UUID `gorm:"type:uuid" json:"related_ban,omitempty"`
	CreatedAt    time.Time  `gorm:"not null" json:"created_at"`
	UpdatedAt    time.Time  `gorm:"not null" json:"updated_at"`
	ResolvedAt   *time.Time `json:"resolved_at,omitempty"`
	ClosedAt     *time.Time `json:"closed_at,omitempty"`

	User     User            `gorm:"foreignKey:UserID" json:"user,omitempty"`
	Assignee *User           `gorm:"foreignKey:AssignedTo" json:"assignee,omitempty"`
	Messages []TicketMessage `gorm:"foreignKey:TicketID" json:"messages,omitempty"`
}

const (
	TicketStatusOpen          = "open"
	TicketStatusAssigned      = "assigned"
	TicketStatusInProgress    = "in_progress"
	TicketStatusWaitingOnUser = "waiting_on_user"
	TicketStatusResolved      = "resolved"
	TicketStatusClosed        = "closed"
	TicketStatusReopened      = "reopened"
)

const (
	TicketCategoryBugReport      = "bug_report"
	TicketCategoryAccountIssue   = "account_issue"
	TicketCategoryBanAppeal      = "ban_appeal"
	TicketCategoryMatchIssue     = "match_issue"
	TicketCategoryFeatureRequest = "feature_request"
	TicketCategoryBilling        = "billing"
	TicketCategoryOther          = "other"
)

func CategoryPriority(category string) int {
	switch category {
	case TicketCategoryAccountIssue, TicketCategoryMatchIssue, TicketCategoryBilling:
		return 2
	case TicketCategoryBugReport, TicketCategoryBanAppeal:
		return 3
	default:
		return 4
	}
}

type TicketMessage struct {
	ID         uuid.UUID `gorm:"type:uuid;default:gen_random_uuid();primaryKey" json:"id"`
	TicketID   uuid.UUID `gorm:"type:uuid;not null;index" json:"ticket_id"`
	AuthorID   uuid.UUID `gorm:"type:uuid;not null" json:"author_id"`
	Content    string    `gorm:"type:text;not null" json:"content"`
	IsInternal bool      `gorm:"default:false" json:"is_internal"`
	CreatedAt  time.Time `gorm:"not null" json:"created_at"`

	Author User `gorm:"foreignKey:AuthorID" json:"author,omitempty"`
}
