import { axiosInstance } from './client';

// ─── Types ────────────────────────────────────────────────────────────────

export type InvoiceStatus = 'draft' | 'sent' | 'paid' | 'partial' | 'void' | 'uncollectible';
export type TransactionType = 'sale' | 'payment' | 'refund' | 'journal' | 'credit' | 'debit' | 'deposit' | 'withdrawal';

export interface QuickbooksInvoice {
  id: string;
  company_id: string;
  qb_doc_id: string;
  connector_id: string;
  invoice_number: string;
  customer_name: string;
  customer_email?: string;
  subtotal: number;
  tax_amount: number;
  total_amount: number;
  due_date: string;
  issue_date: string;
  status: InvoiceStatus;
  line_items?: InvoiceLineItem[];
  notes?: string;
  synced_at: string;
  created_at: string;
}

export interface InvoiceLineItem {
  description: string;
  quantity: number;
  unit_price: number;
  amount: number;
}

export interface QuickbooksTransaction {
  id: string;
  company_id: string;
  qb_doc_id: string;
  connector_id: string;
  transaction_date: string;
  description: string;
  amount: number;
  currency: string;
  transaction_type: TransactionType;
  account_name?: string;
  category?: string;
  synced_at: string;
  created_at: string;
}

export interface QuickbooksCustomer {
  id: string;
  company_id: string;
  qb_doc_id: string;
  connector_id: string;
  name: string;
  email?: string;
  phone?: string;
  address_line1?: string;
  address_city?: string;
  address_state?: string;
  address_zip?: string;
  balance: number;
  total_invoices: number;
  total_paid: number;
  synced_at: string;
  created_at: string;
}

export interface QuickbooksExpense {
  id: string;
  company_id: string;
  qb_doc_id: string;
  connector_id: string;
  expense_date: string;
  vendor_name: string;
  description: string;
  amount: number;
  category: string;
  account_name?: string;
  synced_at: string;
  created_at: string;
}

export interface QuickbooksAnalytics {
  total_invoices: number;
  total_outstanding: number;
  total_paid: number;
  total_partial: number;
  total_void: number;
  total_transactions: number;
  total_customers: number;
  total_expenses: number;
  revenue_last_30d: number;
  revenue_last_90d: number;
  revenue_ytd: number;
  expenses_last_30d: number;
  expenses_last_90d: number;
  profit_margin: number;
  avg_invoice_amount: number;
  avg_collection_days: number;
  invoices_by_status?: { status: string; count: number; total: number }[];
  top_customers?: { name: string; total_paid: number; invoice_count: number }[];
  monthly_revenue?: { month: string; revenue: number }[];
  expense_breakdown?: { category: string; amount: number; count: number }[];
}

// Alias used by pages
export type QuickbooksAnalyticsResponse = QuickbooksAnalytics;
export type InvoicesResponse = { success: boolean; data: { items: QuickbooksInvoice[]; total: number; page: number; per_page: number } };
export type TransactionsResponse = { success: boolean; data: { items: QuickbooksTransaction[]; total: number; page: number; per_page: number } };
export type CustomersResponse = { success: boolean; data: { items: QuickbooksCustomer[]; total: number; page: number; per_page: number } };
export type ExpensesResponse = { success: boolean; data: { items: QuickbooksExpense[]; total: number; page: number; per_page: number } };

// ─── API ──────────────────────────────────────────────────────────────────

const baseUrl = (companyId: string) => `/api/company/${companyId}/quickbooks`;

export const quickbooksApi = {
  // Invoices
  async getInvoices(
    companyId: string,
    params?: { status?: string; customer?: string; date_from?: string; date_to?: string; page?: number; per_page?: number }
  ): Promise<{ success: boolean; data: { items: QuickbooksInvoice[]; total: number; page: number; per_page: number } }> {
    const response = await axiosInstance.get(`${baseUrl(companyId)}/invoices`, { params });
    return response.data;
  },

  async getInvoice(
    companyId: string,
    invoiceId: string
  ): Promise<{ success: boolean; data: QuickbooksInvoice }> {
    const response = await axiosInstance.get(`${baseUrl(companyId)}/invoices/${invoiceId}`);
    return response.data;
  },

  async acceptInvoice(
    companyId: string,
    invoiceId: string
  ): Promise<{ success: boolean; data: QuickbooksInvoice }> {
    const response = await axiosInstance.post(`${baseUrl(companyId)}/accept-invoice/${invoiceId}`);
    return response.data;
  },

  // Transactions
  async getTransactions(
    companyId: string,
    params?: { type?: string; date_from?: string; date_to?: string; page?: number; per_page?: number }
  ): Promise<{ success: boolean; data: { items: QuickbooksTransaction[]; total: number; page: number; per_page: number } }> {
    const response = await axiosInstance.get(`${baseUrl(companyId)}/transactions`, { params });
    return response.data;
  },

  // Customers
  async getCustomers(
    companyId: string,
    params?: { search?: string; page?: number; per_page?: number }
  ): Promise<{ success: boolean; data: { items: QuickbooksCustomer[]; total: number; page: number; per_page: number } }> {
    const response = await axiosInstance.get(`${baseUrl(companyId)}/customers`, { params });
    return response.data;
  },

  // Expenses
  async getExpenses(
    companyId: string,
    params?: { category?: string; vendor?: string; date_from?: string; date_to?: string; page?: number; per_page?: number }
  ): Promise<{ success: boolean; data: { items: QuickbooksExpense[]; total: number; page: number; per_page: number } }> {
    const response = await axiosInstance.get(`${baseUrl(companyId)}/expenses`, { params });
    return response.data;
  },

  // Analytics
  async getAnalytics(companyId: string): Promise<{ success: boolean; data: QuickbooksAnalytics }> {
    const response = await axiosInstance.get(`${baseUrl(companyId)}/analytics`);
    return response.data;
  },

  // Sync
  async sync(companyId: string): Promise<{ success: boolean; data: { message: string } }> {
    const response = await axiosInstance.post(`${baseUrl(companyId)}/sync`);
    return response.data;
  },
};
