package repository

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"

	redislib "gateway/internal/library/redis"
	authdomain "gateway/internal/model/auth/domain"
	domrepo "gateway/internal/model/auth/domain/repository"

	"github.com/zeromicro/go-zero/core/stores/redis"
)

type redisRegistrationSessionStore struct {
	client *redis.Redis
}

// NewRedisRegistrationSessionStore creates a Redis-backed registration session store.
func NewRedisRegistrationSessionStore(client *redislib.Client) domrepo.RegistrationSessionStore {
	if client == nil || client.Zero() == nil {
		panic("auth: redis client is required for registration session store")
	}
	return &redisRegistrationSessionStore{client: client.Zero()}
}

func (s *redisRegistrationSessionStore) Save(ctx context.Context, session *domrepo.RegistrationSession, ttl time.Duration) error {
	if session == nil || session.SessionID == "" {
		return fmt.Errorf("auth: registration session id is required")
	}
	raw, err := json.Marshal(session)
	if err != nil {
		return fmt.Errorf("auth: marshal registration session: %w", err)
	}
	seconds := int(ttl.Seconds())
	if seconds < 1 {
		seconds = 1
	}
	return s.client.SetexCtx(ctx, authdomain.RegistrationSessionRedisKey(session.SessionID), string(raw), seconds)
}

func (s *redisRegistrationSessionStore) Get(ctx context.Context, sessionID string) (*domrepo.RegistrationSession, error) {
	val, err := s.client.GetCtx(ctx, authdomain.RegistrationSessionRedisKey(sessionID))
	if errors.Is(err, redis.Nil) {
		return nil, authdomain.ErrRegistrationSessionNotFound
	}
	if err != nil {
		return nil, err
	}
	var session domrepo.RegistrationSession
	if err := json.Unmarshal([]byte(val), &session); err != nil {
		return nil, fmt.Errorf("auth: unmarshal registration session: %w", err)
	}
	return &session, nil
}

func (s *redisRegistrationSessionStore) Delete(ctx context.Context, sessionID string) error {
	_, err := s.client.DelCtx(ctx, authdomain.RegistrationSessionRedisKey(sessionID))
	return err
}

var _ domrepo.RegistrationSessionStore = (*redisRegistrationSessionStore)(nil)
