import type { Ctx } from "@/lib/auth";
import type { schema } from "@/db";

export type Integration = typeof schema.integrations.$inferSelect;
export type Credentials = Record<string, string | undefined>;

export type ConnectorCategory = "ads" | "analytics" | "messaging" | "payments" | "ai" | "automation" | "collaboration" | "calendar" | "telephony" | "forms";

export type ProviderMeta = {
  key: string;
  name: string;
  category: ConnectorCategory;
  priority: "P1" | "P2" | "P3";
  description: string;
  auth: "oauth" | "credentials" | "webhook" | "none";
  /** credential fields asked for when auth = credentials (or extra config for oauth) */
  fields?: { key: string; label: string; secret?: boolean; placeholder?: string; optional?: boolean }[];
  oauthProvider?: "meta" | "google" | "tiktok" | "linkedin";
  scopes?: string[];
  capabilities: string[];
  docs?: string;
};

export type SyncResult = { ok: boolean; summary: string; records?: number };

export interface Connector {
  meta: ProviderMeta;
  /** validate credentials / finish connection. Returns account reference & display name. */
  connect?(ctx: Ctx, creds: Credentials, config: Record<string, unknown>): Promise<{ accountRef: string; displayName: string; expiresAt?: Date | null; config?: Record<string, unknown> }>;
  /** pull data (metrics, leads, posts) */
  sync?(ctx: Ctx, integration: Integration, creds: Credentials): Promise<SyncResult>;
  /** push data out (conversions, messages, audiences, posts) */
  push?(ctx: Ctx, integration: Integration, creds: Credentials, op: string, payload: Record<string, unknown>): Promise<Record<string, unknown>>;
  /** handle an inbound webhook already verified by verifyWebhook */
  handleWebhook?(ctx: Ctx, integration: Integration | null, body: unknown, headers: Headers): Promise<{ handled: number }>;
  verifyWebhook?(rawBody: string, headers: Headers, creds: Credentials | null): boolean;
  refresh?(ctx: Ctx, integration: Integration, creds: Credentials): Promise<{ creds: Credentials; expiresAt: Date | null }>;
}
