package usecase

import (
	"context"
	"fmt"

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

type siteUseCase struct {
	sites   site.Repository
	statics static.Repository
}

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

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.statics.Fetch(ctx, ""); err == nil {
		for _, res := range out.Resources.Match("index.*.md") {
			out.Languages = append(out.Languages, res.File.Language)
		}
	}

	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
}
