<template>
  <div>
    <h2>Login</h2>
    <form @submit.prevent="executeLogin">
      <input v-model="email" type="email" placeholder="Email" required />
      <input v-model="password" type="password" placeholder="Password" required />
      <button type="submit">Login</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';
import { mapActions } from 'vuex';

export default {
  data() {
    return {
      email: '',
      password: '',
    };
  },
  methods: {
    ...mapActions(['login']),
    async executeLogin() {
      try {
        console.log(import.meta.env.VITE_BACKEND);
        const response = await axios.post(`${import.meta.env.VITE_BACKEND}/api/auth/login`, { email: this.email, password: this.password }, {
          timeout: 5000, 
        });
        await this.login({ token: response.data.token, username: this.email }); 
        this.$router.push('/'); 
      } catch (error) {
        console.error(error);
        alert('Login failed.');
      }
    },
  },
};
</script>
