package api

import (
	"context"
)

type AuthService struct {
	client *Client
}

func NewAuthService(client *Client) *AuthService {
	return &AuthService{client: client}
}

type RegisterRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
	Name     string `json:"name,omitempty"`
}

type LoginRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

type TokenResponse struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type"`
}

func (s *AuthService) Register(ctx context.Context, req RegisterRequest) (*TokenResponse, error) {
	var out TokenResponse
	if err := s.client.doJSON(ctx, "POST", "/api/v1/auth/register", req, &out); err != nil {
		return nil, err
	}
	return &out, nil
}

func (s *AuthService) Login(ctx context.Context, req LoginRequest) (*TokenResponse, error) {
	var out TokenResponse
	if err := s.client.doJSON(ctx, "POST", "/api/v1/auth/login", req, &out); err != nil {
		return nil, err
	}
	return &out, nil
}

func (s *AuthService) Logout(ctx context.Context, token string) error {
	return s.client.WithToken(token).do(ctx, "POST", "/api/v1/auth/logout", nil, nil)
}

func (s *AuthService) Me(ctx context.Context, token string) (*MeResponse, error) {
	var out MeResponse
	if err := s.client.WithToken(token).do(ctx, "GET", "/api/v1/auth/me", nil, &out); err != nil {
		return nil, err
	}
	return &out, nil
}

func (s *AuthService) UpdateMe(ctx context.Context, token string, req UpdateMeRequest) (*MeResponse, error) {
	var out MeResponse
	if err := s.client.WithToken(token).doJSON(ctx, "PATCH", "/api/v1/auth/me", req, &out); err != nil {
		return nil, err
	}
	return &out, nil
}

type ForgotPasswordRequest struct {
	Email string `json:"email"`
}

type ResetPasswordRequest struct {
	Token       string `json:"token"`
	NewPassword string `json:"new_password"`
}

func (s *AuthService) ForgotPassword(ctx context.Context, email string) error {
	return s.client.doJSON(ctx, "POST", "/api/v1/auth/forgot-password", ForgotPasswordRequest{Email: email}, nil)
}

func (s *AuthService) ResetPassword(ctx context.Context, token, newPassword string) error {
	return s.client.doJSON(ctx, "POST", "/api/v1/auth/reset-password", ResetPasswordRequest{
		Token:       token,
		NewPassword: newPassword,
	}, nil)
}
