module Api
  module V1
    class InvitationsController < BaseController
      skip_before_action :authenticate_request!, only: :show

      def show
        invitation = find_pending_invitation
        unless invitation
          return render json: { valid: false, error: "Invito non valido o scaduto" }, status: :not_found
        end

        render json: {
          valid: true,
          email: invitation.email,
          team_id: invitation.team_id,
          team_name: invitation.team.name,
          club_name: invitation.team.club.name,
          staff_kind: invitation.staff_kind,
          expires_at: invitation.expires_at
        }
      end

      def accept
        invitation = find_pending_invitation
        return render json: { error: "Invito non valido o scaduto" }, status: :not_found unless invitation

        if current_user.email.downcase != invitation.email.downcase
          return render json: {
            error: "Questo invito è per #{invitation.email}. Accedi con quell'indirizzo email.",
            invited_email: invitation.email
          }, status: :unprocessable_entity
        end

        invitation.accept!(current_user)
        render json: {
          team_id: invitation.team_id,
          team_name: invitation.team.name,
          message: "Sei entrato in #{invitation.team.name} come responsabile trasmissione."
        }
      end

      private

      def find_pending_invitation
        token = params[:token].to_s
        return nil if token.blank?

        TeamInvitation.pending.find_by(token_digest: Digest::SHA256.hexdigest(token))
      end
    end
  end
end
