<script setup lang="ts">
definePageMeta({ middleware: "guest" });

const email = ref("");
const password = ref("");
const name = ref("");
const age = ref(20);
const errorMsg = ref("");

async function onSubmit() {
  errorMsg.value = "";
  try {
    await $fetch("/api/auth/register", {
      method: "POST",
      body: {
        email: email.value,
        password: password.value,
        name: name.value,
        age: Number(age.value),
      },
      credentials: "include",
    });
    await navigateTo("/me");
  } catch (e: unknown) {
    const err = e as { data?: { error?: { message?: string } } };
    errorMsg.value = err.data?.error?.message ?? "注册失败";
  }
}
</script>

<template>
  <div style="max-width: 360px; margin: 2rem auto; font-family: system-ui">
    <h1>注册</h1>
    <form @submit.prevent="onSubmit">
      <label>
        邮箱
        <input v-model="email" type="email" required style="display: block; width: 100%; margin: 0.25rem 0 1rem" />
      </label>
      <label>
        密码（至少 8 位）
        <input v-model="password" type="password" minlength="8" required style="display: block; width: 100%; margin: 0.25rem 0 1rem" />
      </label>
      <label>
        姓名
        <input v-model="name" type="text" required style="display: block; width: 100%; margin: 0.25rem 0 1rem" />
      </label>
      <label>
        年龄
        <input v-model.number="age" type="number" min="1" max="150" required style="display: block; width: 100%; margin: 0.25rem 0 1rem" />
      </label>
      <p v-if="errorMsg" style="color: crimson">{{ errorMsg }}</p>
      <button type="submit">注册并登录</button>
    </form>
    <p><NuxtLink to="/login">已有账号？登录</NuxtLink></p>
  </div>
</template>
