import { defineStore } from 'pinia';
import { assetsApi } from '../api/assets.js';
import { useWorkspaceStore } from './workspace.js';

export const useAssetsStore = defineStore('assets', {
  state: () => ({
    assets: [],
    loading: false,
    error: null,
  }),

  actions: {
    async fetchAssets() {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return;

      this.loading = true;
      try {
        const response = await assetsApi.list(workspaceStore.currentWorkspaceId);
        this.assets = response.assets || [];
      } catch (err) {
        this.error = err.message;
      } finally {
        this.loading = false;
      }
    },

    async uploadAsset(file) {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return;

      try {
        const asset = await assetsApi.upload(workspaceStore.currentWorkspaceId, file);
        this.assets.unshift(asset);
        return asset;
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

    async deleteAsset(id) {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return;

      try {
        await assetsApi.delete(workspaceStore.currentWorkspaceId, id);
        this.assets = this.assets.filter(a => a.id !== id);
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

    clearAll() {
      this.assets = [];
    },
  },
});
