import { defineStore } from 'pinia';
import type { DraftField } from '../domain/draft';
import type { FieldApplyResult, FillFieldValue } from '../domain/types';

export const useFillerStore = defineStore('filler', {
  state: () => ({ status: 'initializing' as 'initializing' | 'ready' | 'working' | 'error', fields: [] as DraftField[], fieldErrors: {} as Record<string, string>, message: '正在连接文档...' }),
  actions: {
    setDraft(tag: string, value: FillFieldValue) { const field = this.fields.find((item) => item.tag === tag); if (field) field.draftValue = value; },
    applyResults(results: FieldApplyResult[]) {
      this.fieldErrors = {};
      for (const result of results) {
        const field = this.fields.find((item) => item.tag === result.tag);
        if (!field) continue;
        if (result.ok) field.documentValue = field.draftValue;
        else this.fieldErrors[result.tag] = result.error || '应用失败';
      }
    },
  },
});
