import { defineStore } from 'pinia';
import { domainsApi } from '../api/domains.js';
import { useWorkspaceStore } from './workspace.js';

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

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

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

    async addDomain(hostname) {
      const workspaceStore = useWorkspaceStore();
      if (!workspaceStore.currentWorkspaceId) return;

      try {
        const domain = await domainsApi.add(workspaceStore.currentWorkspaceId, hostname);
        this.domains.unshift(domain);
        return domain;
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

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

      try {
        const result = await domainsApi.verify(workspaceStore.currentWorkspaceId, id);
        await this.fetchDomains();
        return result;
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

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

      try {
        await domainsApi.delete(workspaceStore.currentWorkspaceId, id);
        this.domains = this.domains.filter(d => d.id !== id);
      } catch (err) {
        this.error = err.message;
        throw err;
      }
    },

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