import { defineStore } from 'pinia';
import { qrcodesApi } from '../api/qrcodes.js';
import { useWorkspaceStore } from './workspace.js';

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

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

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

    async createQRCode(data) {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return;

      try {
        const qrcode = await qrcodesApi.create(workspaceStore.currentWorkspaceId, data);
        this.qrcodes.unshift(qrcode);
        return qrcode;
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

    async updateQRCode(id, data) {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return;

      try {
        const qrcode = await qrcodesApi.update(workspaceStore.currentWorkspaceId, id, data);
        const index = this.qrcodes.findIndex(q => q.id === id);
        if (index !== -1) {
          this.qrcodes[index] = qrcode;
        }
        return qrcode;
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

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

      try {
        await qrcodesApi.delete(workspaceStore.currentWorkspaceId, id);
        this.qrcodes = this.qrcodes.filter(q => q.id !== id);
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

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

      try {
        return await qrcodesApi.getPreview(workspaceStore.currentWorkspaceId, id);
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

    getQRCodeExportUrl(id, format = 'png', size = 512) {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return null;

      return qrcodesApi.getExportUrl(workspaceStore.currentWorkspaceId, id, format, size);
    },

    async getQRCodeAnalytics(qrCodeId, period = '7d') {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return;

      try {
        return await qrcodesApi.getAnalytics(workspaceStore.currentWorkspaceId, qrCodeId, period);
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

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