export type Provider = "quickbooks" | "xero"

export interface OAuthTokens {
  accessToken: string
  refreshToken: string
  /** ISO timestamp of access-token expiry, or null. */
  expiresAt: string | null
  /** QuickBooks realmId / Xero tenantId. */
  realmId: string | null
  orgName: string | null
}

export interface IncomeEntry {
  externalId: string
  date: string // YYYY-MM-DD
  amount: number
  customerName: string
  description: string
}

export interface ExpenseEntry {
  externalId: string
  date: string // YYYY-MM-DD
  amount: number
  category: string
  vendor: string | null
  description: string
}

export interface AccountingProvider {
  id: Provider
  label: string
  /** True when the provider's OAuth app credentials are configured in env. */
  configured(): boolean
  /** Build the provider's OAuth authorize URL. */
  getAuthUrl(state: string): string
  /** Exchange an authorization code for tokens. `realmId` is QBO's callback param. */
  exchangeCode(code: string, realmId?: string | null): Promise<OAuthTokens>
  /** Refresh an expired access token; returns the new token set (refresh token may rotate). */
  refresh(tokens: OAuthTokens): Promise<OAuthTokens>
  /** Push income (rent) into the books. Returns how many were written. */
  pushIncome(tokens: OAuthTokens, entries: IncomeEntry[]): Promise<{ synced: number }>
  /** Push expenses into the books. */
  pushExpense(tokens: OAuthTokens, entries: ExpenseEntry[]): Promise<{ synced: number }>
}

export function redirectUri(provider: Provider): string {
  const base = (process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000").replace(/\/+$/, "")
  return `${base}/api/integrations/${provider}/callback`
}
