import { create } from 'zustand'
import { apiBase } from '../api/config'

export const useAuthStore = create((set) => ({
      token: null,
      username: null,
      role: null,
      expiresAtUtc: null,
      error: null,
      loading: false,

      login: async (username, password) => {
        set({ loading: true, error: null })
        try {
          const res = await fetch(`${apiBase}/api/auth/login`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ username, password }),
          })
          const data = await res.json().catch(() => ({}))
          if (!res.ok) {
            set({
              loading: false,
              error: data?.title || data || 'Login failed',
              token: null,
              username: null,
              role: null,
            })
            return false
          }
          set({
            loading: false,
            error: null,
            token: data.token,
            username: data.username,
            role: data.role,
            expiresAtUtc: data.expiresAtUtc,
          })
          return true
        } catch (e) {
          set({
            loading: false,
            error: e?.message || 'Cannot reach API. Start HotelPosApi and set VITE_API_URL.',
            token: null,
          })
          return false
        }
      },

      logout: () =>
        set({
          token: null,
          username: null,
          role: null,
          expiresAtUtc: null,
          error: null,
        }),
    }))
