import { create } from 'zustand';
import { apiFetch } from '../lib/api';
import { getDeviceId, getPlatformName } from '../lib/deviceId';

export interface UserDevice {
  id: string;
  deviceId: string;
  platform: string;
  model: string | null;
  name: string | null;
  lastSeenAt: string;
  createdAt: string;
  isCurrent?: boolean;
}

type DevicesState = {
  devices: UserDevice[];
  maxDevices: number;
  plan: string;
  loading: boolean;
  registered: boolean;

  ensureRegistered: () => Promise<void>;
  loadDevices: () => Promise<void>;
  removeDevice: (id: string) => Promise<void>;
};

export const useDevicesStore = create<DevicesState>((set, get) => ({
  devices: [],
  maxDevices: 1,
  plan: 'free',
  loading: false,
  registered: false,

  ensureRegistered: async () => {
    if (get().registered) return;

    const deviceId = await getDeviceId().catch(() => null);
    if (!deviceId) return;

    const platform = getPlatformName();

    await apiFetch('/api/devices/register', {
      method: 'POST',
      skipDeviceHeader: true,
      body: { deviceId, platform },
    }).then((res: any) => {
      set({ registered: true, maxDevices: res.max ?? 1 });
    }).catch(() => {
      // Limit reached or transient — App continues; limit UI is handled at auth level
    });
  },

  loadDevices: async () => {
    set({ loading: true });
    try {
      if (!get().registered) {
        await get().ensureRegistered();
      }
      const res = await apiFetch<{ devices: UserDevice[]; max: number; plan: string }>(
        '/api/devices'
      );
      set({ devices: res.devices, maxDevices: res.max, plan: res.plan });
    } finally {
      set({ loading: false });
    }
  },

  removeDevice: async (id: string) => {
    await apiFetch(`/api/devices/${id}`, { method: 'DELETE' });
    set((s) => ({ devices: s.devices.filter((d) => d.id !== id) }));
  },
}));
