defmodule ToweropsWeb.OrgLive.New do
  @moduledoc false
  use ToweropsWeb, :live_view

  alias Towerops.Organizations
  alias Towerops.Organizations.Organization
  alias Towerops.Organizations.SubscriptionLimits

  @impl true
  def mount(_params, _session, socket) do
    changeset = Organizations.change_organization(%Organization{})
    user = socket.assigns.current_scope.user

    can_create_free = SubscriptionLimits.can_create_free_organization?(user.id)
    free_count = SubscriptionLimits.count_user_owned_free_organizations(user.id)

    {:ok,
     socket
     |> assign(:page_title, "New Organization")
     |> assign(:form, to_form(changeset))
     |> assign(:can_create_free, can_create_free)
     |> assign(:free_org_count, free_count)}
  end

  @impl true
  def handle_event("validate", %{"organization" => org_params}, socket) do
    changeset =
      %Organization{}
      |> Organizations.change_organization(org_params)
      |> Map.put(:action, :validate)

    {:noreply, assign(socket, :form, to_form(changeset))}
  end

  @impl true
  def handle_event("save", %{"organization" => org_params}, socket) do
    user = socket.assigns.current_scope.user
    is_superuser = user.is_superuser
    opts = if is_superuser, do: [bypass_limits: true], else: []

    case Organizations.create_organization(org_params, user.id, opts) do
      {:ok, _organization} ->
        {:noreply,
         socket
         |> put_flash(:info, "Organization created successfully")
         |> push_navigate(to: ~p"/dashboard")}

      {:error, %Ecto.Changeset{} = changeset} ->
        {:noreply, assign(socket, :form, to_form(changeset))}
    end
  end
end
