package service

import (
	"context"
	"errors"
	"strings"

	"wucher/internal/domain/contact"
	"wucher/internal/shared/pkg/sortkey"
)

type pinVerifier interface {
	ConsumeSecurityPINActionToken(ctx context.Context, userID []byte, action, token string) error
}

type ContactService struct {
	repo        contact.Repository
	pinVerifier pinVerifier
}

func NewContactService(repo contact.Repository, pinVerifier pinVerifier) *ContactService {
	return &ContactService{repo: repo, pinVerifier: pinVerifier}
}

func (s *ContactService) ListContacts(ctx context.Context, filter contact.ListFilter) ([]contact.ContactListItem, int64, error) {
	if s.repo == nil {
		return nil, 0, errors.New("contact repository not configured")
	}
	filter.Sort = normalizeContactSort(filter.Sort)
	return s.repo.ListContacts(ctx, filter)
}

func (s *ContactService) GetContactByID(ctx context.Context, userID []byte) (*contact.ContactListItem, error) {
	if s.repo == nil {
		return nil, errors.New("contact repository not configured")
	}
	return s.repo.GetContactByID(ctx, userID)
}

func (s *ContactService) IsActorAdmin(ctx context.Context) (bool, error) {
	if s.repo == nil {
		return false, errors.New("contact repository not configured")
	}
	return s.repo.IsActorAdmin(ctx)
}

func (s *ContactService) ResolveRoleCodeByID(ctx context.Context, roleID []byte) (string, error) {
	if s.repo == nil {
		return "", errors.New("contact repository not configured")
	}
	return s.repo.ResolveRoleCodeByID(ctx, roleID)
}

func (s *ContactService) CreateContact(ctx context.Context, in contact.CreateInput) ([]byte, error) {
	if s.repo == nil {
		return nil, errors.New("contact repository not configured")
	}
	return s.repo.CreateContact(ctx, in)
}

func (s *ContactService) UpdateContact(ctx context.Context, in contact.UpdateInput) error {
	if s.repo == nil {
		return errors.New("contact repository not configured")
	}
	return s.repo.UpdateContact(ctx, in)
}

func (s *ContactService) DeleteContact(ctx context.Context, userID []byte) error {
	if s.repo == nil {
		return errors.New("contact repository not configured")
	}
	return s.repo.DeleteContact(ctx, userID)
}

func (s *ContactService) UpdateContactStatus(ctx context.Context, userID []byte, isActive bool) error {
	if s.repo == nil {
		return errors.New("contact repository not configured")
	}
	return s.repo.UpdateContactStatus(ctx, userID, isActive)
}

func (s *ContactService) UpdateContactRole(ctx context.Context, userID []byte, roleCode string) error {
	if s.repo == nil {
		return errors.New("contact repository not configured")
	}
	return s.repo.UpdateContactRole(ctx, userID, roleCode)
}

func (s *ContactService) UpdatePilotCategory(ctx context.Context, userID []byte, category string) error {
	if s.repo == nil {
		return errors.New("contact repository not configured")
	}
	return s.repo.UpdatePilotCategory(ctx, userID, category)
}

func (s *ContactService) UpdateLicense(ctx context.Context, userID []byte, licenseNo *string) error {
	if s.repo == nil {
		return errors.New("contact repository not configured")
	}
	return s.repo.UpdateLicense(ctx, userID, licenseNo)
}

func (s *ContactService) UpdateChiefFlags(ctx context.Context, userID []byte, patch contact.ProfilePatch) error {
	if s.repo == nil {
		return errors.New("contact repository not configured")
	}
	return s.repo.UpdateChiefFlags(ctx, userID, patch)
}

func (s *ContactService) UpdateResponsibleComplaints(ctx context.Context, userID []byte, value bool) error {
	if s.repo == nil {
		return errors.New("contact repository not configured")
	}
	return s.repo.UpdateResponsibleComplaints(ctx, userID, value)
}

func (s *ContactService) BulkUpdateStatus(ctx context.Context, userIDs [][]byte, isActive bool) (int64, error) {
	if s.repo == nil {
		return 0, errors.New("contact repository not configured")
	}
	return s.repo.BulkUpdateStatus(ctx, userIDs, isActive)
}

func (s *ContactService) CheckSensitiveAction(ctx context.Context, userID []byte, actionToken, action string) error {
	if len(userID) != 16 {
		return ErrInvalidPINAction
	}
	if s.pinVerifier == nil {
		return errors.New("pin verifier not configured")
	}
	action = strings.TrimSpace(action)
	actionToken = strings.TrimSpace(actionToken)
	if action == "" || actionToken == "" {
		return ErrInvalidPINAction
	}
	return s.pinVerifier.ConsumeSecurityPINActionToken(ctx, userID, action, actionToken)
}

func normalizeContactSort(sort string) string {
	return normalizeSortByRules(sort,
		sortExpr(
			joinSortClauses(sortkey.ActivePositiveSortClauses("users", "is_active", "sortkey", "first_name", false)),
			joinSortClauses(sortkey.ActivePositiveSortClauses("users", "is_active", "sortkey", "first_name", true)),
			"sortkey",
		),
		sortExpr(
			"COALESCE(pp.note, dp.note, arp.note, tp.note, fap.note, sp.note, '') ASC",
			"COALESCE(pp.note, dp.note, arp.note, tp.note, fap.note, sp.note, '') DESC",
			"note",
		),
		sortField("users.is_active", "is_active"),
		sortField("users.first_name", "first_name", "name"),
		sortField("users.last_name", "last_name"),
		sortField("users.email", "email"),
		sortField("users.created_at", "created_at"),
		sortField("users.updated_at", "updated_at"),
	)
}
