package usecase

import (
	"context"
	"errors"
	"time"

	authdomain "gateway/internal/model/auth/domain"
	domrepo "gateway/internal/model/auth/domain/repository"
	domusecase "gateway/internal/model/auth/domain/usecase"

	"github.com/google/uuid"
)

type loginSessionUseCase struct {
	store domrepo.LoginSessionStore
}

// LoginSessionUseCaseParam wires LoginSessionUseCase.
type LoginSessionUseCaseParam struct {
	Store domrepo.LoginSessionStore
}

// MustLoginSessionUseCase constructs LoginSessionUseCase.
func MustLoginSessionUseCase(param LoginSessionUseCaseParam) domusecase.LoginSessionUseCase {
	if param.Store == nil {
		panic("auth: login session store is required")
	}
	return &loginSessionUseCase{store: param.Store}
}

func (uc *loginSessionUseCase) Create(ctx context.Context, req *domusecase.CreateLoginSessionRequest) (*domusecase.LoginSessionView, error) {
	if req == nil || req.TenantID == "" || req.TenantSlug == "" {
		return nil, errb.InputMissingRequired("tenant_id and tenant_slug are required")
	}
	if req.Provider == "" {
		return nil, errb.InputMissingRequired("provider is required")
	}
	if req.RedirectURI == "" {
		return nil, errb.InputMissingRequired("redirect_uri is required")
	}
	ttl := req.TTL
	if ttl <= 0 {
		ttl = 10 * time.Minute
	}
	sessionID := uuid.NewString()
	session := &domrepo.LoginSession{
		SessionID:   sessionID,
		TenantID:    req.TenantID,
		TenantSlug:  req.TenantSlug,
		Provider:    req.Provider,
		RedirectURI: req.RedirectURI,
	}
	if err := uc.store.Save(ctx, session, ttl); err != nil {
		return nil, wrapRepoErr(err, "save login session failed")
	}
	return &domusecase.LoginSessionView{
		SessionID: sessionID,
		ExpiresIn: int(ttl.Seconds()),
	}, nil
}

func (uc *loginSessionUseCase) Get(ctx context.Context, sessionID string) (*domusecase.CreateLoginSessionRequest, error) {
	if sessionID == "" {
		return nil, errb.InputMissingRequired("session_id is required")
	}
	session, err := uc.store.Get(ctx, sessionID)
	if err != nil {
		if errors.Is(err, authdomain.ErrLoginSessionNotFound) {
			return nil, errb.ResNotFound("login session", sessionID).WithCause(err)
		}
		return nil, wrapRepoErr(err, "read login session failed")
	}
	return &domusecase.CreateLoginSessionRequest{
		TenantID:    session.TenantID,
		TenantSlug:  session.TenantSlug,
		Provider:    session.Provider,
		RedirectURI: session.RedirectURI,
	}, nil
}

func (uc *loginSessionUseCase) Delete(ctx context.Context, sessionID string) error {
	if sessionID == "" {
		return errb.InputMissingRequired("session_id is required")
	}
	if err := uc.store.Delete(ctx, sessionID); err != nil {
		return wrapRepoErr(err, "delete login session failed")
	}
	return nil
}

var _ domusecase.LoginSessionUseCase = (*loginSessionUseCase)(nil)
