package usecase

import (
	"context"
	"fmt"
	"io"
	"io/fs"

	"source.toby3d.me/toby3d/home/internal/domain"
	"source.toby3d.me/toby3d/home/internal/templateutil"
	"source.toby3d.me/toby3d/home/internal/theme"
)

type (
	themeUseCase struct {
		partials fs.FS
		themes   theme.Repository
	}

	dummyThemeUseCase struct{}
)

func NewThemeUseCase(partials fs.FS, themes theme.Repository) theme.UseCase {
	return &themeUseCase{
		partials: partials,
		themes:   themes,
	}
}

func (ucase *themeUseCase) Do(ctx context.Context, s *domain.Site, e *domain.Entry) (theme.Writer, error) {
	out, err := ucase.themes.Get(ctx, templateutil.New(ucase.partials, s))
	if err != nil {
		return nil, fmt.Errorf("cannot find theme: %w", err)
	}

	return func(w io.Writer) error {
		return out.Lookup("baseof.html").Execute(w, &domain.Context{
			Site: s,
			Page: e,
		})
	}, nil
}

func NewDummyThemeUseCase() theme.UseCase {
	return dummyThemeUseCase{}
}

func (dummyThemeUseCase) Do(_ context.Context, _ *domain.Site, _ *domain.Entry) (theme.Writer, error) {
	return nil, nil
}
