package repository

import (
	"context"
	"database/sql"
	"errors"

	dbgen "github.com/SamuelTariku/FortuneBet-Backend/gen/db"
	"github.com/SamuelTariku/FortuneBet-Backend/internal/domain"
	"github.com/SamuelTariku/FortuneBet-Backend/internal/services/authentication"
	"github.com/jackc/pgx/v5/pgtype"
)
  
func (s *Store) GetUserByEmailPhone(ctx context.Context, email, phone string) (domain.User, error) {
	user, err := s.queries.GetUserByEmailPhone(ctx, dbgen.GetUserByEmailPhoneParams{
		Email: pgtype.Text{
			String: email,
			Valid:  true,
		},
		PhoneNumber: pgtype.Text{
			String: phone,
			Valid:  true,
		},
	})
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return domain.User{}, authentication.ErrUserNotFound
		}
		return domain.User{}, err
	}
	return domain.User{
		ID:            user.ID,
		FirstName:     user.FirstName,
		LastName:      user.LastName,
		Email:         user.Email.String,
		PhoneNumber:   user.PhoneNumber.String,
		Password:      user.Password,
		Role:          domain.Role(user.Role),
		EmailVerified: user.EmailVerified,
		PhoneVerified: user.PhoneVerified,
		CreatedAt:     user.CreatedAt.Time,
		UpdatedAt:     user.UpdatedAt.Time,
		SuspendedAt:   user.SuspendedAt.Time,
		Suspended:     user.Suspended,
		CompanyID: domain.ValidInt64{
			Value: user.CompanyID.Int64,
			Valid: user.CompanyID.Valid,
		},
	}, nil

}

func (s *Store) CreateRefreshToken(ctx context.Context, rt domain.RefreshToken) error {
	return s.queries.CreateRefreshToken(ctx, dbgen.CreateRefreshTokenParams{
		UserID: rt.UserID,
		Token:  rt.Token,
		CreatedAt: pgtype.Timestamptz{
			Time:  rt.CreatedAt,
			Valid: true,
		},
		ExpiresAt: pgtype.Timestamptz{
			Time:  rt.ExpiresAt,
			Valid: true,
		},
		Revoked: rt.Revoked,
	})

}
func (s *Store) GetRefreshToken(ctx context.Context, token string) (domain.RefreshToken, error) {
	rf, err := s.queries.GetRefreshToken(ctx, token)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return domain.RefreshToken{}, authentication.ErrRefreshTokenNotFound
		}
		return domain.RefreshToken{}, err
	}
	return domain.RefreshToken{
		Token:     rf.Token,
		UserID:    rf.UserID,
		CreatedAt: rf.CreatedAt.Time,
		ExpiresAt: rf.ExpiresAt.Time,
		Revoked:   rf.Revoked,
	}, nil
}

func (s *Store) GetRefreshTokenByUserID(ctx context.Context, id int64) (domain.RefreshToken, error) {
	rf, err := s.queries.GetRefreshTokenByUserID(ctx, id)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return domain.RefreshToken{}, authentication.ErrRefreshTokenNotFound
		}
		return domain.RefreshToken{}, err
	}

	return domain.RefreshToken{
		Token:     rf.Token,
		UserID:    rf.UserID,
		CreatedAt: rf.CreatedAt.Time,
		ExpiresAt: rf.ExpiresAt.Time,
		Revoked:   rf.Revoked,
	}, nil
}

func (s *Store) RevokeRefreshToken(ctx context.Context, token string) error {
	return s.queries.RevokeRefreshToken(ctx, token)
}
