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 redisLoginSessionStore struct {
	client *redis.Redis
}

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

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

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

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

var _ domrepo.LoginSessionStore = (*redisLoginSessionStore)(nil)
