import { defineStore } from 'pinia'
import { uploadService } from '../../services/uploadService.js'

export const useUploadStore = defineStore('upload', {
  state: () => ({
    file: null,
    scanReport: null,
    conversionResult: null,
    status: 'idle', // idle | scanning | scanned | converting | complete | error
    error: null,
  }),
  actions: {
    async scan(file) {
      this.file = file
      this.status = 'scanning'
      this.error = null
      this.scanReport = null
      this.conversionResult = null
      try {
        this.scanReport = await uploadService.scan(file)
        this.status = 'scanned'
      } catch (e) {
        this.error = e.message
        this.status = 'error'
      }
    },
    async convert() {
      this.status = 'converting'
      this.error = null
      try {
        this.conversionResult = await uploadService.convert(this.scanReport.sessionId, this.file?.name)
        this.status = 'complete'
      } catch (e) {
        this.error = e.message === 'INSUFFICIENT_CREDITS' ? 'INSUFFICIENT_CREDITS' : e.message
        this.status = 'error'
      }
    },
    reset() {
      this.file = null
      this.scanReport = null
      this.conversionResult = null
      this.status = 'idle'
      this.error = null
    },
  },
})
