package usecase

import (
	"context"
	"strings"

	"haixun-backend/internal/library/clock"
	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/model/publish_queue_event/domain/entity"
	domrepo "haixun-backend/internal/model/publish_queue_event/domain/repository"
	domusecase "haixun-backend/internal/model/publish_queue_event/domain/usecase"

	"github.com/google/uuid"
)

type eventUseCase struct {
	repo domrepo.Repository
}

func NewUseCase(repo domrepo.Repository) domusecase.UseCase {
	return &eventUseCase{repo: repo}
}

func (u *eventUseCase) Record(ctx context.Context, req domusecase.RecordRequest) error {
	if strings.TrimSpace(req.TenantID) == "" || strings.TrimSpace(req.OwnerUID) == "" {
		return app.For(code.Auth).AuthUnauthorized("missing actor")
	}
	if strings.TrimSpace(req.AccountID) == "" || strings.TrimSpace(req.QueueID) == "" {
		return app.For(code.ThreadsAccount).InputMissingRequired("account_id and queue_id are required")
	}
	eventType := strings.TrimSpace(req.EventType)
	if eventType == "" {
		eventType = entity.EventCreated
	}
	return u.repo.Create(ctx, &entity.Event{
		ID:         uuid.NewString(),
		TenantID:   strings.TrimSpace(req.TenantID),
		OwnerUID:   strings.TrimSpace(req.OwnerUID),
		AccountID:  strings.TrimSpace(req.AccountID),
		QueueID:    strings.TrimSpace(req.QueueID),
		EventType:  eventType,
		FromStatus: strings.TrimSpace(req.FromStatus),
		ToStatus:   strings.TrimSpace(req.ToStatus),
		Message:    strings.TrimSpace(req.Message),
		CreateAt:   clock.NowUnixNano(),
	})
}

func (u *eventUseCase) ListByQueue(ctx context.Context, tenantID, ownerUID, accountID, queueID string, limit int) ([]domusecase.EventSummary, error) {
	items, err := u.repo.ListByQueue(ctx, tenantID, ownerUID, accountID, queueID, limit)
	if err != nil {
		return nil, err
	}
	return toSummaries(items), nil
}

func (u *eventUseCase) ListRecentByAccount(ctx context.Context, tenantID, ownerUID, accountID string, limit int) ([]domusecase.EventSummary, error) {
	items, err := u.repo.ListRecentByAccount(ctx, tenantID, ownerUID, accountID, limit)
	if err != nil {
		return nil, err
	}
	return toSummaries(items), nil
}

func toSummaries(items []entity.Event) []domusecase.EventSummary {
	out := make([]domusecase.EventSummary, 0, len(items))
	for _, item := range items {
		out = append(out, domusecase.EventSummary{
			ID: item.ID, QueueID: item.QueueID, AccountID: item.AccountID, EventType: item.EventType,
			FromStatus: item.FromStatus, ToStatus: item.ToStatus, Message: item.Message, CreateAt: item.CreateAt,
		})
	}
	return out
}
