package systemconfig

import (
	"context"
	"encoding/json"
)

func (s *Service) HomeAnnouncements(ctx context.Context) (*HomeAnnouncementsDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	items, err := s.homeAnnouncements(ctx)
	if err != nil {
		return nil, err
	}
	return &HomeAnnouncementsDTO{Items: items}, nil
}

func (s *Service) HomeConfig(ctx context.Context) (*HomeConfigDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	announcements, err := s.homeAnnouncements(ctx)
	if err != nil {
		return nil, err
	}
	banners, err := s.homeBanners(ctx)
	if err != nil {
		return nil, err
	}
	publishOptions, err := s.publishOptions(ctx)
	if err != nil {
		return nil, err
	}
	return &HomeConfigDTO{
		Announcements:  announcements,
		Banners:        banners,
		PublishOptions: publishOptions,
	}, nil
}

func (s *Service) homeAnnouncements(ctx context.Context) ([]string, error) {
	value, err := s.repo.FindValue(ctx, homeAnnouncementsConfigKey)
	if err != nil {
		return nil, err
	}
	items := defaultHomeAnnouncements()
	if err := json.Unmarshal([]byte(value), &items); err != nil {
		items = defaultHomeAnnouncements()
	}
	return normalizeAnnouncements(items), nil
}

func (s *Service) homeBanners(ctx context.Context) ([]HomeBannerItem, error) {
	value, err := s.repo.FindValue(ctx, homeBannersConfigKey)
	if err != nil {
		return nil, err
	}
	items := defaultHomeBanners()
	if err := json.Unmarshal([]byte(value), &items); err != nil {
		items = defaultHomeBanners()
	}
	return normalizeHomeBanners(items), nil
}
