<!-- pages/views in vue are basically root-level full-page components -->

<script setup lang="ts">

import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";

import { useUsersStore } from "../stores/UsersStore.ts";
import type { User } from "../models/User.ts";

const store = useUsersStore();
const route = useRoute();
const router = useRouter();

const user = ref<User>({
    id: 0,
    name: "",
    email: "",
    password: ""
});

const id: string | undefined = route.params.id as string | undefined

onMounted(() => {
    if(id) {
        const existing = store.users.find(i => i.id == Number(id));
        if (existing) user.value = { ...existing };
    }
});

async function save(): Promise<void> {
    if(id) {
        await store.updateUser(Number(id), user.value);
    } else {
        await store.addUser(user.value);
    }

    router.push("/users"); // redirect
}

</script>

<template>

    <div>
        <h2>{{ id ? "Edit User" : "Create User" }}</h2> <!-- omg I love ternary operator :D -->

        <form @submit.prevent="save">
            <input v-model="user.name" placeholder="Name" />
            
            <button type="submit">Save</button>
        </form>
    </div>

</template>