<script setup lang="ts">
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { apiPost } from "../api";
import { authState, updateAuthSession } from "../auth";
import FormStatus from "../components/FormStatus.vue";
import PageHeader from "../components/PageHeader.vue";

const router = useRouter();
const form = reactive({
  current_password: "",
  new_password: "",
  new_password_confirm: ""
});
const pending = ref(false);
const status = ref("");
const statusKind = ref<"info" | "success" | "error">("info");

async function submit() {
  if (form.new_password !== form.new_password_confirm) {
    status.value = "Die neuen Passwörter stimmen nicht überein.";
    statusKind.value = "error";
    return;
  }

  pending.value = true;
  status.value = "Sende Anfrage...";
  statusKind.value = "info";

  const result = await apiPost("/api/v1/auth/change-initial-password", {
    email: authState.session?.email ?? "",
    ...form
  });
  pending.value = false;

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

  updateAuthSession({ mustChangePassword: false });
  router.push("/setup/organization");
}
</script>

<template>
  <PageHeader title="Initialpasswort ändern" description="Nach dem ersten Login muss ein eigenes Passwort gesetzt werden." />
  <section class="panel form-panel">
    <form @submit.prevent="submit">
      <label class="field">
        <span>Aktuelles Passwort</span>
        <input v-model="form.current_password" type="password" required />
      </label>
      <label class="field">
        <span>Neues Passwort</span>
        <input v-model="form.new_password" type="password" required />
      </label>
      <label class="field">
        <span>Neues Passwort wiederholen</span>
        <input v-model="form.new_password_confirm" type="password" required />
      </label>
      <div class="form-actions">
        <button type="submit" :disabled="pending">Passwort speichern</button>
      </div>
      <FormStatus :message="status" :kind="statusKind" />
    </form>
  </section>
</template>
