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

const email = ref("");
const password = ref("");
const errorMsg = ref("");

async function onSubmit() {
  errorMsg.value = "";
  try {
    await $fetch("/api/auth/login", {
      method: "POST",
      body: { email: email.value, password: password.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>
        密码
        <input v-model="password" type="password" minlength="8" 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="/register">没有账号？注册</NuxtLink></p>
  </div>
</template>
