import { defineStore } from 'pinia';
import { authApi } from '../api/auth.js';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token'),
    loading: false,
    error: null,
    initialized: false,
  }),

  getters: {
    isAuthenticated: (state) => !!state.token,
  },

  actions: {
    async initialize() {
      if (this.initialized) return;

      if (this.token) {
        authApi.setToken(this.token);
        try {
          const profile = await authApi.getProfile();
          this.user = profile;
        } catch (err) {
          this.logout();
        }
      }
      this.initialized = true;
    },

    async register(email, password) {
      this.loading = true;
      this.error = null;
      try {
        const response = await authApi.register(email, password);
        this.token = response.token;
        this.user = { email: response.email, isVerified: false };
        localStorage.setItem('token', response.token);
        authApi.setToken(response.token);
        return true;
      } catch (err) {
        this.error = err.message;
        return false;
      } finally {
        this.loading = false;
      }
    },

    async login(email, password) {
      this.loading = true;
      this.error = null;
      try {
        const response = await authApi.login(email, password);
        this.token = response.token;
        this.user = { email: response.email };
        localStorage.setItem('token', response.token);
        authApi.setToken(response.token);
        return true;
      } catch (err) {
        this.error = err.message;
        return false;
      } finally {
        this.loading = false;
      }
    },

    logout() {
      this.token = null;
      this.user = null;
      localStorage.removeItem('token');
      localStorage.removeItem('currentWorkspaceId');
      authApi.setToken(null);
    },

    async fetchProfile() {
      try {
        this.user = await authApi.getProfile();
      } catch (err) {
        this.error = err.message;
      }
    },
  },
});
