module Api
  module V1
    class AuthController < ApplicationController
      skip_before_action :authenticate_request!, only: %i[login refresh register]

      def register
        user = User.new(
          email: params[:email]&.downcase,
          name: params[:name],
          password: params[:password],
          role: "coach"
        )
        if user.save
          render json: token_response(user), status: :created
        else
          render json: { error: user.errors.full_messages.join(", ") }, status: :unprocessable_entity
        end
      end

      def login
        user = User.find_by(email: params[:email]&.downcase)
        if user&.authenticate(params[:password])
          render json: token_response(user), status: :ok
        else
          render json: { error: "Invalid credentials" }, status: :unauthorized
        end
      end

      def logout
        render json: { message: "Logged out" }
      end

      def refresh
        payload = JsonWebToken.decode(params[:refresh_token] || bearer_token)
        user = User.find_by(id: payload&.dig(:user_id))
        return render json: { error: "Invalid token" }, status: :unauthorized unless user

        render json: token_response(user)
      end

      def me
        render json: user_json(current_user)
      end

      private

      def token_response(user)
        {
          user: user_json(user),
          access_token: JsonWebToken.encode({ user_id: user.id, type: "access" }),
          refresh_token: JsonWebToken.encode({ user_id: user.id, type: "refresh" }, exp: 30.days.from_now)
        }
      end

      def user_json(user)
        {
          id: user.id,
          email: user.email,
          name: user.name,
          role: user.role
        }
      end
    end
  end
end
