package services

import (
	"fmt"
	"time"

	"github.com/google/uuid"
	"github.com/tapper/backend/database"
	"github.com/tapper/backend/models"
)

func CreateTicket(userID uuid.UUID, category, subject, body string, userTier string) (*models.Ticket, error) {
	priority := models.CategoryPriority(category)

	if userTier == "vip" && priority > 1 {
		priority--
	}

	var relatedBan *uuid.UUID
	if category == models.TicketCategoryBanAppeal {
		ban := GetActiveBan(userID)
		if ban != nil {
			relatedBan = &ban.ID
		}
	}

	ticket := models.Ticket{
		UserID:     userID,
		Category:   category,
		Priority:   priority,
		Status:     models.TicketStatusOpen,
		Subject:    subject,
		RelatedBan: relatedBan,
	}

	if err := database.DB.Create(&ticket).Error; err != nil {
		return nil, fmt.Errorf("failed to create ticket: %w", err)
	}

	msg := models.TicketMessage{
		TicketID: ticket.ID,
		AuthorID: userID,
		Content:  body,
	}
	if err := database.DB.Create(&msg).Error; err != nil {
		return nil, fmt.Errorf("failed to create initial message: %w", err)
	}

	return &ticket, nil
}

func AddTicketMessage(ticketID, authorID uuid.UUID, content string, isInternal bool) (*models.TicketMessage, error) {
	msg := models.TicketMessage{
		TicketID:   ticketID,
		AuthorID:   authorID,
		Content:    content,
		IsInternal: isInternal,
	}
	if err := database.DB.Create(&msg).Error; err != nil {
		return nil, err
	}

	database.DB.Model(&models.Ticket{}).Where("id = ?", ticketID).
		Update("updated_at", time.Now().UTC())

	return &msg, nil
}

func CloseTicket(ticketID uuid.UUID) error {
	now := time.Now().UTC()
	return database.DB.Model(&models.Ticket{}).Where("id = ?", ticketID).
		Updates(map[string]interface{}{
			"status":    models.TicketStatusClosed,
			"closed_at": now,
			"updated_at": now,
		}).Error
}

func EscalateTicket(ticketID uuid.UUID) error {
	now := time.Now().UTC()
	return database.DB.Model(&models.Ticket{}).Where("id = ?", ticketID).
		Updates(map[string]interface{}{
			"priority":   1,
			"status":     models.TicketStatusOpen,
			"updated_at": now,
		}).Error
}

func AssignTicket(ticketID, assigneeID uuid.UUID) error {
	now := time.Now().UTC()
	return database.DB.Model(&models.Ticket{}).Where("id = ?", ticketID).
		Updates(map[string]interface{}{
			"assigned_to": assigneeID,
			"status":      models.TicketStatusAssigned,
			"updated_at":  now,
		}).Error
}
