import { create } from 'zustand'
import { legalApi } from '@/lib/api'

export interface Contract {
  id: string
  title: string
  type: string
  customer_id: string
  value: number
  currency: string
  start_date: string
  end_date: string
  status: string
}

interface LegalState {
  contracts: Contract[]
  templates: unknown[]
  loading: boolean
  error: string | null
  fetchContracts: () => Promise<void>
  fetchTemplates: () => Promise<void>
  createContract: (data: Partial<Contract>) => Promise<void>
}

export const useLegalStore = create<LegalState>((set, get) => ({
  contracts: [],
  templates: [],
  loading: false,
  error: null,

  fetchContracts: async () => {
    set({ loading: true, error: null })
    try {
      const data = await legalApi.contracts()
      set({ contracts: (data.contracts || []) as Contract[], loading: false })
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to fetch contracts', loading: false })
    }
  },

  fetchTemplates: async () => {
    set({ loading: true, error: null })
    try {
      const data = await legalApi.templates()
      set({ templates: (data.templates || []) as unknown[], loading: false })
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to fetch templates', loading: false })
    }
  },

  createContract: async (data) => {
    set({ loading: true, error: null })
    try {
      await legalApi.createContract(data)
      await get().fetchContracts()
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to create contract', loading: false })
    }
  },
}))
