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

const requestForm = reactive({ email: "" });
const resetForm = reactive({ token: "", new_password: "", new_password_confirm: "" });
const status = ref("");
const kind = ref<"info" | "success" | "error">("info");

async function requestReset() {
  const result = await apiPost<{ queued: boolean; dev_reset_token?: string }>("/api/v1/auth/request-password-reset", requestForm);
  status.value = result.ok
    ? `Reset-E-Mail wurde vorbereitet.${result.data.dev_reset_token ? ` Dev-Token: ${result.data.dev_reset_token}` : ""}`
    : result.message;
  kind.value = result.ok ? "success" : "error";
}

async function resetPassword() {
  const result = await apiPost("/api/v1/auth/reset-password", resetForm);
  status.value = result.ok ? "Passwort wurde geändert." : result.message;
  kind.value = result.ok ? "success" : "error";
}
</script>

<template>
  <PageHeader title="Passwort zurücksetzen" description="Reset-Link anfordern und neues Passwort setzen." />
  <section class="panel form-panel">
    <form @submit.prevent="requestReset">
      <label class="field"><span>E-Mail-Adresse</span><input v-model="requestForm.email" type="email" required /></label>
      <div class="form-actions"><button type="submit">Reset anfordern</button></div>
    </form>
  </section>
  <section class="panel form-panel">
    <form @submit.prevent="resetPassword">
      <label class="field"><span>Reset-Token</span><input v-model="resetForm.token" required /></label>
      <label class="field"><span>Neues Passwort</span><input v-model="resetForm.new_password" type="password" required /></label>
      <label class="field"><span>Neues Passwort wiederholen</span><input v-model="resetForm.new_password_confirm" type="password" required /></label>
      <div class="form-actions"><button type="submit">Passwort setzen</button></div>
      <FormStatus :message="status" :kind="kind" />
    </form>
  </section>
</template>
