import { defineStore } from 'pinia'
import api from 'src/services/api'

export const useTranslationStore = defineStore('translation', {
  state: () => ({
    loading: false,
    saving: false,
    rows: [],
    count: 0
  }),

  actions: {
    async fetchRows (filters = {}, options = {}) {
      this.loading = true
      const append = Boolean(options?.append)
      try {
        const res = await api.get('/language/translations', { params: filters })
        const payload = res?.data || {}
        const incoming = Array.isArray(payload.rows) ? payload.rows : []
        if (append) {
          const merged = [...this.rows]
          const seen = new Set(this.rows.map((x) => x?.id))
          for (const row of incoming) {
            const id = row?.id
            if (!seen.has(id)) {
              merged.push(row)
              seen.add(id)
            }
          }
          this.rows = merged
        } else {
          this.rows = incoming
        }
        this.count = Number(payload.count) || this.rows.length
      } finally {
        this.loading = false
      }
    },

    async updateRow (id, payload) {
      this.saving = true
      try {
        const res = await api.put(`/language/translations/${id}`, payload)
        return res?.data || null
      } finally {
        this.saving = false
      }
    },

    async upsertMissing (items, languages = ['en', 'de', 'it', 'es', 'ru', 'ar']) {
      this.saving = true
      try {
        const res = await api.post('/language/translations/upsert-missing', {
          items: Array.isArray(items) ? items : [],
          languages: Array.isArray(languages) ? languages : []
        })
        return res?.data || null
      } finally {
        this.saving = false
      }
    },

    async syncSources (payload = {}) {
      this.saving = true
      const startedAt = Date.now()
      console.info('[translation-sync][frontend] request:start', {
        at: new Date(startedAt).toISOString(),
        payload
      })
      try {
        const res = await api.post('/language/translations/sync-sources', payload, { timeout: 0 })
        const data = res?.data || null
        const traceId = data?.trace_id || data?.result?.trace_id || res?.headers?.['x-trace-id'] || null
        console.info('[translation-sync][frontend] request:success', {
          trace_id: traceId,
          duration_ms: Date.now() - startedAt,
          result: data?.result || null
        })
        return data
      } catch (err) {
        console.error('[translation-sync][frontend] request:error', {
          duration_ms: Date.now() - startedAt,
          message: err?.message || 'sync-sources failed'
        })
        throw err
      } finally {
        this.saving = false
      }
    },

    async translateSelected (payload = {}) {
      this.saving = true
      const startedAt = Date.now()
      console.info('[translation-selected][frontend] request:start', {
        at: new Date(startedAt).toISOString(),
        payload
      })
      try {
        const res = await api.post('/language/translations/translate-selected', payload, { timeout: 0 })
        const data = res?.data || null
        const traceId = data?.trace_id || res?.headers?.['x-trace-id'] || null
        console.info('[translation-selected][frontend] request:success', {
          trace_id: traceId,
          duration_ms: Date.now() - startedAt,
          translated_count: data?.translated_count || 0
        })
        return data
      } catch (err) {
        console.error('[translation-selected][frontend] request:error', {
          duration_ms: Date.now() - startedAt,
          message: err?.message || 'translate-selected failed'
        })
        throw err
      } finally {
        this.saving = false
      }
    },

    async bulkApprove (ids = []) {
      this.saving = true
      try {
        const res = await api.post('/language/translations/bulk-approve', {
          ids: Array.isArray(ids) ? ids : []
        })
        return res?.data || null
      } finally {
        this.saving = false
      }
    },

    async bulkUpdate (items = []) {
      this.saving = true
      try {
        const res = await api.post('/language/translations/bulk-update', {
          items: Array.isArray(items) ? items : []
        })
        return res?.data || null
      } finally {
        this.saving = false
      }
    }
  }
})
