<script setup>
import { hydrateUser } from "../../composables/useAuth.js";
import { api, ensureCsrf } from "../../services/api.js";

import Button from "primevue/button";
import Column from "primevue/column";
import DataTable from "primevue/datatable";
import InputSwitch from "primevue/inputswitch";
import Message from "primevue/message";

import { onMounted, ref } from "vue";

const loading = ref(false);
const savingSlug = ref("");
const error = ref("");
const modules = ref([]);

async function load() {
  loading.value = true;
  error.value = "";
  try {
    await ensureCsrf();
    const { data } = await api.get("/api/superadmin/modules");
    modules.value = Array.isArray(data?.data) ? data.data : [];
  } catch (e) {
    error.value =
      e?.response?.data?.message || "Could not load modules. Forbidden?";
    modules.value = [];
  } finally {
    loading.value = false;
  }
}

async function toggle(row, nextEnabled) {
  savingSlug.value = row.slug;
  error.value = "";
  try {
    await ensureCsrf();
    await api.patch(`/api/superadmin/modules/${row.slug}`, {
      is_enabled: nextEnabled,
    });
    row.is_enabled = nextEnabled;
    await hydrateUser();
  } catch (e) {
    error.value =
      e?.response?.data?.message || "Could not update module. Try again.";
    row.is_enabled = !nextEnabled;
  } finally {
    savingSlug.value = "";
  }
}

onMounted(() => {
  load();
});
</script>

<template>
  <div>
    <h1 class="title-h5 mb-4">Feature modules</h1>
    <p class="body-small text-surface-600 dark:text-surface-400 mb-6">
      Toggles write to the database and are the
      <strong class="font-medium text-surface-700 dark:text-surface-300"
        >runtime switch</strong
      >
      for each module: sidebar, <code class="text-xs px-1">/api/user</code>
      (<code class="text-xs px-1">enabled_module_slugs</code>), SPA routes with
      <code class="text-xs px-1">meta.module</code>, and (for Customers) the
      <code class="text-xs px-1">/api/customers</code> API. Turning a module off
      here blocks it everywhere for normal users.
      <span class="block mt-2 text-surface-500 dark:text-surface-500">
        To ship an app
        <em>without</em> customer routes or code paths at all, set
        <code class="text-xs px-1 rounded bg-surface-100 dark:bg-surface-800"
          >config/core.php</code
        >
        <code class="text-xs px-1">modules.customers</code> to
        <code class="text-xs px-1">false</code> (deploy-time); that is separate
        from this screen.
      </span>
    </p>
    <Message v-if="error" severity="error" class="mb-4" :closable="false">
      {{ error }}
    </Message>
    <Message
      v-if="!loading && !error && modules.length === 0"
      severity="warn"
      class="mb-4"
      :closable="false"
    >
      No feature modules are in the database yet. From the Laravel app that
      mounts Maestro Core, run
      <code class="text-sm px-1 rounded bg-surface-100 dark:bg-surface-800"
        >php artisan migrate</code
      >
      then seed navigation/modules, for example:
      <code class="text-sm px-1 rounded bg-surface-100 dark:bg-surface-800"
        >php artisan db:seed --class=&quot;Maestro\\Core\\Database\\Seeders\\ModuleAndNavigationSeeder&quot;</code
      >
      (or your full <code class="text-sm px-1">DatabaseSeeder</code> if it calls
      that seeder).
    </Message>
    <div class="flex justify-end mb-3">
      <Button
        label="Refresh"
        icon="pi pi-refresh"
        severity="secondary"
        outlined
        :loading="loading"
        @click="load"
      />
    </div>
    <DataTable :value="modules" data-key="slug" striped-rows>
      <Column field="label" header="Module" />
      <Column field="slug" header="Slug" />
      <Column header="Enabled" style="width: 8rem">
        <template #body="{ data }">
          <InputSwitch
            :model-value="Boolean(data.is_enabled)"
            :disabled="loading || savingSlug === data.slug"
            @update:model-value="(v) => toggle(data, v)"
          />
        </template>
      </Column>
    </DataTable>
  </div>
</template>
