<script setup lang="ts">
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { apiPost } from "../api";
import { setAuthSession } from "../auth";
import FormStatus from "../components/FormStatus.vue";
import PageHeader from "../components/PageHeader.vue";
import { ensureConnection } from "../realtime";
import type { DevBootstrapResponse, LoginResponse } from "../types";

const router = useRouter();
const form = reactive({
  email: "",
  password: ""
});
const pending = ref(false);
const status = ref("");
const statusKind = ref<"info" | "success" | "error">("info");
const devForm = reactive({
  organization_name: "Lokale Testfirma",
  email: "admin@example.test"
});
const devPending = ref(false);
const devStatus = ref("");
const devStatusKind = ref<"info" | "success" | "error">("info");
const devCredentials = ref<DevBootstrapResponse | null>(null);

async function submit() {
  pending.value = true;
  status.value = "Sende Anfrage...";
  statusKind.value = "info";

  const result = await apiPost<LoginResponse>("/api/v1/auth/login", form);
  pending.value = false;

  if (!result.ok) {
    status.value = result.message;
    statusKind.value = "error";
    return;
  }

  setAuthSession({
    email: form.email,
    userId: result.data.user_id,
    accessToken: result.data.access_token,
    organizationId: result.data.organization_id ?? result.data.organizations[0]?.id ?? null,
    mustChangePassword: result.data.must_change_password
  });
  ensureConnection();
  router.push(result.data.must_change_password ? "/change-initial-password" : "/");
}

async function bootstrapDev() {
  devPending.value = true;
  devStatus.value = "Lege lokale Testfirma an...";
  devStatusKind.value = "info";
  devCredentials.value = null;

  const result = await apiPost<DevBootstrapResponse>("/api/v1/dev/bootstrap-local", devForm);
  devPending.value = false;

  if (!result.ok) {
    devStatus.value = result.message;
    devStatusKind.value = "error";
    return;
  }

  devCredentials.value = result.data;
  form.email = result.data.email;
  form.password = result.data.password;
  devStatus.value = "Testfirma und User wurden angelegt.";
  devStatusKind.value = "success";
}
</script>

<template>
  <PageHeader title="Login" description="Anmeldung mit E-Mail-Adresse und Passwort." />
  <section class="panel form-panel">
    <form @submit.prevent="submit">
      <label class="field">
        <span>E-Mail-Adresse</span>
        <input v-model="form.email" name="email" type="email" placeholder="admin@example.com" required />
      </label>
      <label class="field">
        <span>Passwort</span>
        <input v-model="form.password" name="password" type="password" required />
      </label>
      <div class="form-actions">
        <button type="submit" :disabled="pending">Einloggen</button>
      </div>
      <FormStatus :message="status" :kind="statusKind" />
    </form>
  </section>
  <section class="panel form-panel">
    <div class="section-title">
      <div>
        <h2>Dev-Bootstrap</h2>
        <p class="muted">Lokale Testfirma mit erstem User anlegen, ohne E-Mail-Versand.</p>
      </div>
    </div>
    <form @submit.prevent="bootstrapDev">
      <label class="field">
        <span>Firmenname</span>
        <input v-model="devForm.organization_name" type="text" required />
      </label>
      <label class="field">
        <span>E-Mail-Adresse</span>
        <input v-model="devForm.email" type="email" required />
      </label>
      <div class="form-actions">
        <button type="submit" :disabled="devPending">Testfirma und User anlegen</button>
      </div>
      <FormStatus :message="devStatus" :kind="devStatusKind" />
    </form>
    <dl v-if="devCredentials" class="detail-grid dev-credentials">
      <dt>Login</dt><dd>{{ devCredentials.email }}</dd>
      <dt>Passwort</dt><dd><code>{{ devCredentials.password }}</code></dd>
      <dt>Firma</dt><dd><code>{{ devCredentials.organization_id }}</code></dd>
      <dt>Schema</dt><dd><code>{{ devCredentials.schema_name }}</code></dd>
    </dl>
  </section>
</template>
