package usecase

import (
	"context"
	"fmt"

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

type (
	siteUseCase struct {
		sites     site.Repository
		resources resource.Repository
	}

	stubSiteUseCase struct {
		err  error
		site *domain.Site
	}
)

func NewSiteUseCase(sites site.Repository, resources resource.Repository) site.UseCase {
	return &siteUseCase{
		sites:     sites,
		resources: resources,
	}
}

func (ucase *siteUseCase) Do(ctx context.Context, lang domain.Language) (*domain.Site, error) {
	out, err := ucase.sites.Get(ctx, domain.LanguageUnd)
	if err != nil {
		return nil, fmt.Errorf("cannot find base site data: %w", err)
	}

	if out.Resources, _, err = ucase.resources.Fetch(ctx, ""); err == nil {
		for _, res := range out.Resources.Match("index.*.md") {
			out.Languages = append(out.Languages, res.File.Language)
		}
	}

	if !out.IsMultiLingual() {
		out.Language = out.DefaultLanguage
	}

	sub, err := ucase.sites.Get(ctx, lang)
	if err != nil {
		return out, nil
	}

	out.Language = sub.Language

	for k, v := range sub.Params {
		out.Params[k] = v
	}

	return out, nil
}

func NewStubSiteUseCase(site *domain.Site, err error) site.UseCase {
	return &stubSiteUseCase{
		site: site,
		err:  err,
	}
}

func (ucase *stubSiteUseCase) Do(_ context.Context, _ domain.Language) (*domain.Site, error) {
	return ucase.site, ucase.err
}
