package usecase

import (
	"context"
	"fmt"
	"strings"

	"source.toby3d.me/toby3d/home/internal/domain"
	"source.toby3d.me/toby3d/home/internal/site"
	"source.toby3d.me/toby3d/home/internal/webfinger"
)

type webFingerUseCase struct {
	sites site.Repository
}

func NewWebFingerUseCase(sites site.Repository) webfinger.UseCase {
	return &webFingerUseCase{sites: sites}
}

func (ucase *webFingerUseCase) Do(ctx context.Context, acct string) (*domain.Site, error) {
	parts := strings.Split(acct, "@")
	if len(parts) != 2 {
		return nil, fmt.Errorf("invalid 'acct' value format, got %s, want [user, host]", parts)
	}

	site, err := ucase.sites.Get(ctx, domain.LanguageUnd)
	if err != nil {
		return nil, fmt.Errorf("cannot read global site config: %w", err)
	}

	if !strings.EqualFold(parts[1], site.BaseURL.Hostname()) {
		return nil, fmt.Errorf("requested %s user outside %s resource", parts[1], site.BaseURL.Hostname())
	}

	return site, nil
}
