module Public
  class TeamsController < WebBaseController
    before_action :require_login!
    before_action :set_team, only: %i[
      dashboard billing checkout portal invite create_invitation
      remove_member destroy_invitation
    ]

    def new
      redirect_to public_team_dashboard_path(current_user.teams.first) if current_user.teams.any?
    end

    def create
      if current_user.user_teams.where(role: "owner").exists?
        redirect_to public_team_dashboard_path(current_user.teams.first), alert: "Hai già una squadra"
        return
      end

      team = Team.create!(team_params)
      UserTeam.create!(user: current_user, team: team, role: "owner")
      plan = params[:plan].presence_in(%w[free premium_light premium_full]) || "free"
      Billing::AssignPlan.call(team: team, plan_slug: plan)

      if plan.in?(%w[premium_light premium_full]) && MatchLiveTv.stripe_enabled?
        redirect_to public_team_checkout_path(team, plan: plan)
      else
        redirect_to public_team_dashboard_path(team), notice: "Squadra creata con piano Free"
      end
    end

    def dashboard
      require_team_owner!(@team)
      @entitlements = @team.entitlements
      @recordings = @team.recordings.ready.includes(stream_session: :match).order(created_at: :desc).limit(10)
      @members = @team.user_teams.includes(:user).where.not(role: "owner")
      @pending_invitations = @team.team_invitations.pending.order(created_at: :desc)
    end

    def billing
      require_team_owner!(@team)
      @entitlements = @team.entitlements
      @plans = Plan.ordered
    end

    def checkout
      require_team_owner!(@team)
      unless MatchLiveTv.stripe_enabled?
        redirect_to public_team_billing_path(@team), alert: "Pagamenti non ancora configurati sul server"
        return
      end

      plan_slug = params[:plan].presence_in(%w[premium_light premium_full]) || "premium_light"
      url = Billing::Stripe::CheckoutSession.new(team: @team, user: current_user, plan_slug: plan_slug).url
      redirect_to url, allow_other_host: true
    end

    def portal
      require_team_owner!(@team)
      unless MatchLiveTv.stripe_enabled?
        redirect_to public_team_billing_path(@team), alert: "Portale pagamenti non configurato"
        return
      end

      url = Billing::Stripe::CheckoutSession.new(team: @team, user: current_user).portal_url
      redirect_to url, allow_other_host: true
    end

    def invite
      require_team_owner!(@team)
      @entitlements = @team.entitlements
    end

    def create_invitation
      require_team_owner!(@team)
      @entitlements = @team.entitlements
      staff_kind = params[:staff_kind].presence_in(TeamInvitation::STAFF_KINDS) || "transmission"
      @entitlements.assert_can_invite!(staff_kind: staff_kind)

      email = params[:email]&.downcase&.strip
      token = TeamInvitation.generate_token
      @team.team_invitations.create!(
        email: email,
        token_digest: Digest::SHA256.hexdigest(token),
        role: "member",
        staff_kind: staff_kind,
        expires_at: 7.days.from_now
      )
      @invite_url = join_public_invitation_url(token: token)
      flash.now[:notice] = "Link invito generato (valido 7 giorni)"
      render :invite
    rescue Teams::EntitlementError => e
      redirect_to public_team_invite_path(@team), alert: e.message
    end

    def remove_member
      require_team_owner!(@team)
      ut = @team.user_teams.find_by!(user_id: params[:user_id], role: "member")
      ut.destroy!
      redirect_to public_team_dashboard_path(@team), notice: "Accesso revocato"
    end

    def destroy_invitation
      require_team_owner!(@team)
      inv = @team.team_invitations.pending.find(params[:invitation_id])
      inv.destroy!
      redirect_to public_team_dashboard_path(@team), notice: "Invito annullato"
    end

    private

    def set_team
      @team = current_user.teams.find(params[:id])
    end

    def team_params
      params.require(:team).permit(:name, :sport, :logo_url)
    end
  end
end
