package api

import (
	"context"
	"strconv"
	"time"

	aapi "git.vdhsn.com/barretthousen/barretthousen/src/auth/api/grpc"
	"git.vdhsn.com/barretthousen/barretthousen/src/auth/internal/domain"
	"google.golang.org/grpc"
)

func NewAuthServiceClient(conn grpc.ClientConnInterface) *AuthServiceClient {
	return &AuthServiceClient{
		AuthClient: aapi.NewAuthClient(conn),
	}
}

type AuthServiceClient struct {
	aapi.AuthClient
}

type CheckSessionParams struct {
	SessionID string
}

func (asc *AuthServiceClient) CheckSession(ctx context.Context, in CheckSessionParams) (out Account, err error) {
	if in.SessionID == "" {
		err = domain.ErrInvalidSession
		return
	}
	var sessionIDInt int

	if sessionIDInt, err = strconv.Atoi(in.SessionID); err != nil {
		return
	}
	var accountResult *aapi.Account

	if accountResult, err = asc.GetSession(ctx, &aapi.SessionFilter{
		SessionId: int32(sessionIDInt),
	}); err != nil {
		return
	}

	out = Account{
		ID:       int(accountResult.Id),
		Created:  accountResult.CreatedTs.AsTime(),
		Email:    accountResult.Email,
		Verified: accountResult.VerifiedTs.AsTime(),
		Role:     accountResult.Role,
	}

	return
}

type Account struct {
	ID           int       `json:"id"`
	Created      time.Time `json:"created"`
	Verified     time.Time `json:"verified,omitempty"`
	Email        string    `json:"email"`
	PasswordHash string    `json:"password_hash,omitempty"`
	Role         string    `json:"role"`
	Enabled      bool      `json:"enabled"`
}
