package checkups

import (
	"context"
	"errors"
	"fmt"

	"apps/backend/internal/logic/growthmap"
	"apps/backend/internal/middleware"
	growthDomain "apps/backend/internal/module/growth/domain"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetLatestCheckupLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetLatestCheckupLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLatestCheckupLogic {
	return &GetLatestCheckupLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}

func (l *GetLatestCheckupLogic) GetLatestCheckup() (*types.WeeklyCheckupPublic, error) {
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok || uid <= 0 {
		return nil, fmt.Errorf("unauthorized")
	}
	c, err := l.svcCtx.Growth.LatestCheckup(l.ctx, uid)
	if err != nil {
		if errors.Is(err, growthDomain.ErrNotFound) {
			// auto-generate first
			c, err = l.svcCtx.Growth.GenerateCheckup(l.ctx, uid, "", false)
			if err != nil {
				return nil, err
			}
			return growthmap.Checkup(c), nil
		}
		return nil, err
	}
	return growthmap.Checkup(c), nil
}
