package chat

import (
	"context"
	"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(ctx context.Context, principal Principal, page, pageSize int) (*PaginatedResult, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.ListConversations(ctx, principal, page, pageSize)
}

func (s *Service) CountUnreadMessages(ctx context.Context, principal Principal) (*UnreadCountDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	total, err := s.repo.CountUnreadMessages(ctx, principal)
	if err != nil {
		return nil, err
	}
	return &UnreadCountDTO{UnreadCount: total}, nil
}

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

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

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

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

func (s *Service) SendMessage(ctx context.Context, 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(ctx, 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(ctx context.Context, principal Principal, conversationID uint64) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	return s.repo.MarkRead(ctx, principal, conversationID)
}

func (s *Service) TransferConversation(ctx context.Context, 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(ctx, principal, conversationID, req.ToAdminID)
}

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

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

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

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

func (s *Service) CreateQuickReply(ctx context.Context, 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(ctx, adminID, req)
}

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

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

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

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

func (s *Service) GetListingGroupWelcomeMessage(ctx context.Context) string {
	if s.repo == nil {
		return ""
	}
	return s.repo.GetListingGroupWelcomeMessage(ctx)
}

func (s *Service) UpdateListingGroupWelcomeMessage(ctx context.Context, message string) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	return s.repo.UpdateListingGroupWelcomeMessage(ctx, message)
}
