package inquiry

import (
	"time"
	"tm/pkg/mongo"

	"go.mongodb.org/mongo-driver/v2/bson"
)

// Inquiry status constants
const (
	StatusPending   = "pending"   // درحال بررسی
	StatusReviewed  = "reviewed"  // بررسی شده
	StatusApproved  = "approved"  // تایید شده
	StatusRejected  = "rejected"  // رد شده
)

// StatusHistory represents a status change record
type StatusHistory struct {
	Status      string `bson:"status" json:"status"`           // New status
	Reason      string `bson:"reason" json:"reason"`           // Reason for change
	ChangedBy   string `bson:"changed_by" json:"changed_by"`   // User who made the change
	ChangedAt   int64  `bson:"changed_at" json:"changed_at"`   // Timestamp of change
	Description string `bson:"description" json:"description"` // Optional description
}

type Inquiry struct {
	mongo.Model     `bson:",inline"`
	FullName        string           `bson:"full_name"`
	CompanyName     string           `bson:"company_name"`
	WorkEmail       string           `bson:"work_email"`
	PhoneNumber     string           `bson:"phone_number"`
	Status          string           `bson:"status"`           // Current status
	StatusHistory   []StatusHistory  `bson:"status_history"`   // History of status changes
}

func (i *Inquiry) SetID(id string) {
	i.ID, _ = bson.ObjectIDFromHex(id)
}

func (i *Inquiry) GetID() string {
	return i.ID.Hex()
}

func (i *Inquiry) SetCreatedAt(timestamp int64) {
	i.CreatedAt = timestamp
}

func (i *Inquiry) SetUpdatedAt(timestamp int64) {
	i.UpdatedAt = timestamp
}

func (i *Inquiry) GetCreatedAt() int64 {
	return i.CreatedAt
}

func (i *Inquiry) GetUpdatedAt() int64 {
	return i.UpdatedAt
}

// AddStatusChange adds a new status change to the history
func (i *Inquiry) AddStatusChange(status, reason, changedBy, description string) {
	statusChange := StatusHistory{
		Status:      status,
		Reason:      reason,
		ChangedBy:   changedBy,
		ChangedAt:   time.Now().Unix(),
		Description: description,
	}
	
	i.StatusHistory = append(i.StatusHistory, statusChange)
	i.Status = status
	i.SetUpdatedAt(time.Now().Unix())
}

// GetCurrentStatus returns the current status
func (i *Inquiry) GetCurrentStatus() string {
	return i.Status
}

// GetLastStatusChange returns the most recent status change
func (i *Inquiry) GetLastStatusChange() *StatusHistory {
	if len(i.StatusHistory) == 0 {
		return nil
	}
	return &i.StatusHistory[len(i.StatusHistory)-1]
}
