package chat

import (
	"errors"
	"net/url"
	"strings"
)

var (
	ErrDependencyUnavailable = errors.New("dependency unavailable")
	ErrConversationNotFound  = errors.New("conversation not found")
	ErrPermissionDenied      = errors.New("permission denied")
	ErrInvalidMessage        = errors.New("invalid message")
)

type Service struct {
	repo *Repository
}

func NewService(repo *Repository) *Service {
	return &Service{repo: repo}
}

func (s *Service) ListConversations(principal Principal, page, pageSize int) (*PaginatedResult, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.ListConversations(principal, page, pageSize)
}

func (s *Service) FindConversation(principal Principal, id uint64) (*ConversationDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.FindConversation(principal, id)
}

func (s *Service) FindOrderConversation(userID uint64, orderID uint64) (*ConversationDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.FindOrderConversation(userID, orderID)
}

func (s *Service) EnsureSupportConversation(userID uint64) (*ConversationDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	if userID == 0 {
		return nil, ErrPermissionDenied
	}
	return s.repo.EnsureSupportConversation(userID)
}

func (s *Service) Messages(principal Principal, conversationID uint64, page, pageSize int) (*PaginatedResult, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.Messages(principal, conversationID, page, pageSize)
}

func (s *Service) SendMessage(principal Principal, conversationID uint64, req SendMessageRequest) (*MessageDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	req.Content = strings.TrimSpace(req.Content)
	attachments, ok := normalizeAttachmentURLS(req.AttachmentURLS)
	req.AttachmentURLS = attachments
	if conversationID == 0 || (req.Content == "" && len(req.AttachmentURLS) == 0) {
		return nil, ErrInvalidMessage
	}
	if len([]rune(req.Content)) > 1000 {
		return nil, ErrInvalidMessage
	}
	if !ok {
		return nil, ErrInvalidMessage
	}
	return s.repo.SendMessage(principal, conversationID, req)
}

func normalizeAttachmentURLS(items []string) ([]string, bool) {
	if len(items) > 9 {
		return nil, false
	}
	result := make([]string, 0, len(items))
	for _, item := range items {
		value := strings.TrimSpace(item)
		if value == "" {
			continue
		}
		if len(value) > 500 || strings.Contains(value, "..") {
			return nil, false
		}
		parsed, err := url.Parse(value)
		if err != nil {
			return nil, false
		}
		if parsed.Host != "" {
			return nil, false
		}
		switch parsed.Path {
		case "/api/files/object", "/api/admin/files/object", "/api/public/files/object":
		default:
			return nil, false
		}
		key := strings.TrimSpace(parsed.Query().Get("key"))
		if key == "" || strings.Contains(key, "..") {
			return nil, false
		}
		result = append(result, value)
	}
	return result, true
}

func (s *Service) MarkRead(principal Principal, conversationID uint64) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	return s.repo.MarkRead(principal, conversationID)
}

func (s *Service) TransferConversation(principal Principal, conversationID uint64, req TransferRequest) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	if conversationID == 0 || req.ToAdminID == 0 {
		return ErrInvalidMessage
	}
	return s.repo.TransferConversation(principal, conversationID, req.ToAdminID)
}

func (s *Service) GetAvailableSupportAdmins() ([]SupportAdminDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.GetAvailableSupportAdmins()
}

func (s *Service) ListConversationsWithFilter(principal Principal, page, pageSize int, filter string) (*PaginatedResult, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.ListConversationsWithFilter(principal, page, pageSize, filter)
}

func (s *Service) UpdateRemark(principal Principal, conversationID uint64, req UpdateRemarkRequest) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	return s.repo.UpdateRemark(principal, conversationID, req.Remark)
}

func (s *Service) ListQuickReplies(adminID uint64) ([]QuickReplyDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.ListQuickReplies(adminID)
}

func (s *Service) CreateQuickReply(adminID uint64, req CreateQuickReplyRequest) (*QuickReplyDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	req.Title = strings.TrimSpace(req.Title)
	req.Content = strings.TrimSpace(req.Content)
	if req.Title == "" || req.Content == "" {
		return nil, ErrInvalidMessage
	}
	return s.repo.CreateQuickReply(adminID, req)
}

func (s *Service) UpdateQuickReply(adminID uint64, replyID uint64, req UpdateQuickReplyRequest) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	return s.repo.UpdateQuickReply(adminID, replyID, req)
}

func (s *Service) DeleteQuickReply(adminID uint64, replyID uint64) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	return s.repo.DeleteQuickReply(adminID, replyID)
}

func (s *Service) GetAutoWelcomeMessage() string {
	if s.repo == nil {
		return ""
	}
	return s.repo.GetAutoWelcomeMessage()
}

func (s *Service) UpdateAutoWelcomeMessage(message string) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	return s.repo.UpdateAutoWelcomeMessage(message)
}
