import { useQuery, UseQueryOptions } from '@tanstack/react-query';
import { gql } from 'graphql-request';
import { fetchGraphQL, createQueryKey } from '../client';
import type { JournalEntryDraft } from '@/types/accounting';

// GraphQL Queries
const JOURNAL_ENTRY_DRAFTS_QUERY = gql`
  query JournalEntryDrafts($companyId: ID!) {
    journalEntryDrafts(companyId: $companyId) {
      id
      companyId
      name
      voucherNumber
      documentDate
      description
      fiscalYearId
      lines {
        lineNumber
        accountId
        debitAmount
        creditAmount
        description
        vatCode
      }
      attachmentIds
      status
      transactionId
      createdBy
      createdAt
      updatedAt
    }
  }
`;

const JOURNAL_ENTRY_DRAFT_QUERY = gql`
  query JournalEntryDraft($id: ID!) {
    journalEntryDraft(id: $id) {
      id
      companyId
      name
      voucherNumber
      documentDate
      description
      fiscalYearId
      lines {
        lineNumber
        accountId
        debitAmount
        creditAmount
        description
        vatCode
      }
      attachmentIds
      status
      transactionId
      createdBy
      createdAt
      updatedAt
    }
  }
`;

// Response types
interface JournalEntryDraftsResponse {
  journalEntryDrafts: JournalEntryDraft[];
}

interface JournalEntryDraftResponse {
  journalEntryDraft: JournalEntryDraft | null;
}

/**
 * Hook to fetch all active journal entry drafts for a company.
 */
export function useJournalEntryDrafts(
  companyId: string | undefined,
  options?: Omit<UseQueryOptions<JournalEntryDraft[], Error>, 'queryKey' | 'queryFn'>
) {
  return useQuery({
    queryKey: createQueryKey('journalEntryDrafts', { companyId }),
    queryFn: async () => {
      if (!companyId) return [];
      const data = await fetchGraphQL<JournalEntryDraftsResponse>(
        JOURNAL_ENTRY_DRAFTS_QUERY,
        { companyId }
      );
      return data.journalEntryDrafts;
    },
    enabled: !!companyId,
    ...options,
  });
}

/**
 * Hook to fetch a single journal entry draft by ID.
 */
export function useJournalEntryDraft(
  id: string | undefined,
  options?: Omit<UseQueryOptions<JournalEntryDraft | null, Error>, 'queryKey' | 'queryFn'>
) {
  return useQuery({
    queryKey: createQueryKey('journalEntryDraft', { id }),
    queryFn: async () => {
      if (!id) return null;
      const data = await fetchGraphQL<JournalEntryDraftResponse>(
        JOURNAL_ENTRY_DRAFT_QUERY,
        { id }
      );
      return data.journalEntryDraft;
    },
    enabled: !!id,
    ...options,
  });
}
