// internal/models/revision_log.go
package models

import (
	"time"

	"gorm.io/gorm"
)

// RevisionLog represents revision history for item edits
type RevisionLog struct {
	ID         uint           `gorm:"primaryKey" json:"id"`
	ItemID     uint           `gorm:"not null" json:"item_id"`
	Item       Item           `gorm:"foreignKey:ItemID" json:"item,omitempty"`
	UserID     uint           `gorm:"not null" json:"user_id"` // Who made the edit
	User       User           `gorm:"foreignKey:UserID" json:"user,omitempty"`
	FieldName  string         `gorm:"type:varchar(50);not null" json:"field_name"` // Which field was edited
	OldValue   string         `gorm:"type:text" json:"old_value"`
	NewValue   string         `gorm:"type:text" json:"new_value"`
	Reason     string         `gorm:"type:text" json:"reason"` // Why was it edited
	CreatedAt  time.Time      `json:"created_at"`
	DeletedAt  gorm.DeletedAt `gorm:"index" json:"-"`
}

// TableName specifies the table name for RevisionLog model
func (RevisionLog) TableName() string {
	return "revision_logs"
}

// RevisionLogResponse represents revision log data for API responses
type RevisionLogResponse struct {
	ID         uint      `json:"id"`
	ItemID     uint      `json:"item_id"`
	UserName   string    `json:"user_name"`
	FieldName  string    `json:"field_name"`
	OldValue   string    `json:"old_value"`
	NewValue   string    `json:"new_value"`
	Reason     string    `json:"reason"`
	CreatedAt  time.Time `json:"created_at"`
}

// ToResponse converts RevisionLog to RevisionLogResponse
func (rl *RevisionLog) ToResponse() RevisionLogResponse {
	userName := ""
	if rl.User.ID != 0 {
		userName = rl.User.Name
	}

	return RevisionLogResponse{
		ID:        rl.ID,
		ItemID:    rl.ItemID,
		UserName:  userName,
		FieldName: rl.FieldName,
		OldValue:  rl.OldValue,
		NewValue:  rl.NewValue,
		Reason:    rl.Reason,
		CreatedAt: rl.CreatedAt,
	}
}

// CreateRevisionLog creates a new revision log entry
func CreateRevisionLog(db *gorm.DB, itemID, userID uint, fieldName, oldValue, newValue, reason string) error {
	log := &RevisionLog{
		ItemID:    itemID,
		UserID:    userID,
		FieldName: fieldName,
		OldValue:  oldValue,
		NewValue:  newValue,
		Reason:    reason,
	}

	return db.Create(log).Error
}