/**
 * Unified data model (BRD §9).
 * Every tenant table carries workspace_id plus created_at / updated_at / created_by.
 * IDs are UUIDs; money is stored as integer minor units (paisa / cents) with a currency code.
 */
import {
  pgTable, uuid, text, timestamp, integer, bigint, boolean, jsonb, date, index, uniqueIndex, real,
} from "drizzle-orm/pg-core";
import { sql } from "drizzle-orm";

const id = () => uuid("id").primaryKey().default(sql`gen_random_uuid()`);
const ts = (name: string) => timestamp(name, { withTimezone: true, mode: "date" });
const audit = () => ({
  createdAt: ts("created_at").notNull().defaultNow(),
  updatedAt: ts("updated_at").notNull().defaultNow(),
  createdBy: uuid("created_by"),
});
const tenant = () => uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" });

/* ---------------- Tenancy & access (ADM, AUTH) ---------------- */

export const agencies = pgTable("agencies", {
  id: id(),
  name: text("name").notNull(),
  branding: jsonb("branding").$type<Branding>().notNull().default({}),
  plan: text("plan").notNull().default("agency"),
  billingCustomerId: text("billing_customer_id"),
  ...audit(),
});

export const workspaces = pgTable("workspaces", {
  id: id(),
  agencyId: uuid("agency_id").references(() => agencies.id, { onDelete: "set null" }),
  name: text("name").notNull(),
  slug: text("slug").notNull(),
  /** secret key used in inbound webhook URLs: /api/v1/hooks/{key}/{source} */
  hookKey: text("hook_key").notNull(),
  timezone: text("timezone").notNull().default("Asia/Dhaka"),
  currency: text("currency").notNull().default("BDT"),
  locale: text("locale").notNull().default("en"),
  plan: text("plan").notNull().default("growth"),
  settings: jsonb("settings").$type<WorkspaceSettings>().notNull().default({}),
  /* subscription (lib/plans.ts) — existing workspaces stay "active" */
  subscriptionStatus: text("subscription_status").notNull().default("active"), // trialing | active | past_due | canceled
  trialEndsAt: ts("trial_ends_at"),
  currentPeriodEnd: ts("current_period_end"),
  billingCustomerId: text("billing_customer_id"),
  billingSubscriptionId: text("billing_subscription_id"),
  ...audit(),
}, (t) => [uniqueIndex("workspaces_slug_uq").on(t.slug), uniqueIndex("workspaces_hook_uq").on(t.hookKey)]);

export const users = pgTable("users", {
  id: id(),
  email: text("email").notNull(),
  name: text("name").notNull(),
  phone: text("phone"),
  passwordHash: text("password_hash"),
  googleSub: text("google_sub"),
  mfaEnabled: boolean("mfa_enabled").notNull().default(false),
  mfaSecret: text("mfa_secret"),
  status: text("status").notNull().default("active"), // active | invited | disabled
  isAgencyAdmin: boolean("is_agency_admin").notNull().default(false),
  agencyId: uuid("agency_id").references(() => agencies.id, { onDelete: "set null" }),
  locale: text("locale"),
  lastLoginAt: ts("last_login_at"),
  /* verification & account protection */
  emailVerifiedAt: ts("email_verified_at"),
  phoneVerifiedAt: ts("phone_verified_at"),
  failedLogins: integer("failed_logins").notNull().default(0),
  lockedUntil: ts("locked_until"),
  passwordChangedAt: ts("password_changed_at"),
  ...audit(),
}, (t) => [uniqueIndex("users_email_uq").on(t.email)]);

/**
 * Two-factor methods per user: authenticator app (TOTP), email code, SMS code, passkey / security key (WebAuthn).
 * Secrets are AES-256-GCM encrypted; codes are stored only as hashes.
 */
export const mfaMethods = pgTable("mfa_methods", {
  id: id(),
  userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
  type: text("type").notNull(), // totp | email | sms | webauthn
  label: text("label"),
  target: text("target"), // email address / E.164 phone (email & sms)
  secretEnc: text("secret_enc"), // encrypted TOTP secret
  credentialId: text("credential_id"), // WebAuthn credential id (base64url)
  publicKey: text("public_key"), // WebAuthn COSE public key (base64url)
  counter: integer("counter").notNull().default(0),
  transports: text("transports").array().notNull().default(sql`'{}'::text[]`),
  lastUsedStep: integer("last_used_step"), // TOTP replay protection
  verifiedAt: ts("verified_at"),
  lastUsedAt: ts("last_used_at"),
  createdAt: ts("created_at").notNull().defaultNow(),
}, (t) => [index("mfa_methods_user_idx").on(t.userId), uniqueIndex("mfa_methods_cred_uq").on(t.credentialId)]);

/** One-time recovery codes (hashed). */
export const mfaBackupCodes = pgTable("mfa_backup_codes", {
  id: id(),
  userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
  codeHash: text("code_hash").notNull(),
  usedAt: ts("used_at"),
  createdAt: ts("created_at").notNull().defaultNow(),
}, (t) => [index("mfa_backup_user_idx").on(t.userId)]);

/** Pending email/SMS codes and WebAuthn challenges (login, enrolment, step-up). */
export const mfaChallenges = pgTable("mfa_challenges", {
  id: id(),
  userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
  sessionId: uuid("session_id"),
  methodId: uuid("method_id"),
  purpose: text("purpose").notNull(), // login | enroll | step_up
  kind: text("kind").notNull(), // code | webauthn
  codeHash: text("code_hash"),
  challenge: text("challenge"),
  attempts: integer("attempts").notNull().default(0),
  expiresAt: ts("expires_at").notNull(),
  consumedAt: ts("consumed_at"),
  createdAt: ts("created_at").notNull().defaultNow(),
}, (t) => [index("mfa_challenges_user_idx").on(t.userId, t.createdAt)]);

/** "Remember this device for 30 days" after a successful second factor. */
export const trustedDevices = pgTable("trusted_devices", {
  id: id(),
  userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
  tokenHash: text("token_hash").notNull(),
  userAgent: text("user_agent"),
  ip: text("ip"),
  expiresAt: ts("expires_at").notNull(),
  lastUsedAt: ts("last_used_at"),
  createdAt: ts("created_at").notNull().defaultNow(),
}, (t) => [uniqueIndex("trusted_devices_token_uq").on(t.tokenHash)]);

export const roles = pgTable("roles", {
  id: id(),
  workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade" }), // null = system default
  key: text("key").notNull(),
  name: text("name").notNull(),
  permissions: jsonb("permissions").$type<Record<string, string>>().notNull(),
  isSystem: boolean("is_system").notNull().default(false),
  ...audit(),
});

export const memberships = pgTable("memberships", {
  id: id(),
  workspaceId: tenant(),
  userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
  roleId: uuid("role_id").notNull().references(() => roles.id),
  territory: text("territory"),
  projects: text("projects").array().notNull().default(sql`'{}'::text[]`),
  active: boolean("active").notNull().default(true),
  team: text("team"), // SOC-070/073 routing teams, e.g. sales | support
  availability: text("availability").notNull().default("online"), // online | away
  socialAccountIds: uuid("social_account_ids").array().notNull().default(sql`'{}'::uuid[]`), // SOC-091: empty = all accounts
  /** personal dashboard: ordered widget ids + hidden ids (null = industry default) */
  dashboardLayout: jsonb("dashboard_layout").$type<{ order: string[]; hidden: string[] } | null>(),
  ...audit(),
}, (t) => [uniqueIndex("memberships_uq").on(t.workspaceId, t.userId)]);

/** Self-serve sign-up in progress: email + phone verified by one-time codes before the account exists. */
export const registrations = pgTable("registrations", {
  id: id(),
  email: text("email").notNull(),
  phone: text("phone").notNull(),
  name: text("name").notNull(),
  passwordHash: text("password_hash").notNull(),
  emailCodeHash: text("email_code_hash"),
  phoneCodeHash: text("phone_code_hash"),
  emailVerifiedAt: ts("email_verified_at"),
  phoneVerifiedAt: ts("phone_verified_at"),
  attempts: integer("attempts").notNull().default(0),
  sends: integer("sends").notNull().default(0),
  lastSentAt: ts("last_sent_at"),
  ip: text("ip"),
  expiresAt: ts("expires_at").notNull(),
  completedAt: ts("completed_at"),
  createdAt: ts("created_at").notNull().defaultNow(),
}, (t) => [index("registrations_email_idx").on(t.email)]);

export const sessions = pgTable("sessions", {
  id: id(),
  userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
  workspaceId: uuid("workspace_id"),
  mfaPassed: boolean("mfa_passed").notNull().default(false),
  mfaMethod: text("mfa_method"), // how the second factor was satisfied (totp | email | sms | webauthn | backup | trusted_device)
  lastSeenAt: ts("last_seen_at"),
  expiresAt: ts("expires_at").notNull(),
  userAgent: text("user_agent"),
  ip: text("ip"),
  createdAt: ts("created_at").notNull().defaultNow(),
});

export const apiKeys = pgTable("api_keys", {
  id: id(),
  workspaceId: tenant(),
  name: text("name").notNull(),
  prefix: text("prefix").notNull(),
  hashedKey: text("hashed_key").notNull(),
  scopes: text("scopes").array().notNull(),
  lastUsedAt: ts("last_used_at"),
  revokedAt: ts("revoked_at"),
  ...audit(),
}, (t) => [uniqueIndex("api_keys_hash_uq").on(t.hashedKey)]);

export const auditLogs = pgTable("audit_logs", {
  id: id(),
  workspaceId: uuid("workspace_id"),
  actorType: text("actor_type").notNull(), // user | agent | system | api_key
  actorId: text("actor_id"),
  actorName: text("actor_name"),
  action: text("action").notNull(),
  objectType: text("object_type").notNull(),
  objectId: text("object_id"),
  before: jsonb("before"),
  after: jsonb("after"),
  ip: text("ip"),
  at: ts("at").notNull().defaultNow(),
}, (t) => [index("audit_ws_at_idx").on(t.workspaceId, t.at)]);

/* ---------------- Unified customer data (CDP) ---------------- */

export const contacts = pgTable("contacts", {
  id: id(),
  workspaceId: tenant(),
  firstName: text("first_name"),
  lastName: text("last_name"),
  phones: text("phones").array().notNull().default(sql`'{}'::text[]`),
  emails: text("emails").array().notNull().default(sql`'{}'::text[]`),
  socialIds: jsonb("social_ids").$type<Record<string, string>>().notNull().default({}),
  ownerId: uuid("owner_id"),
  lifecycleStage: text("lifecycle_stage").notNull().default("lead"),
  score: integer("score"),
  scoreReason: text("score_reason"),
  city: text("city"),
  territory: text("territory"),
  project: text("project"),
  source: text("source"),
  customFields: jsonb("custom_fields").$type<Record<string, unknown>>().notNull().default({}),
  tags: text("tags").array().notNull().default(sql`'{}'::text[]`),
  mergedIntoId: uuid("merged_into_id"),
  firstContactedAt: ts("first_contacted_at"),
  lastActivityAt: ts("last_activity_at"),
  deletedAt: ts("deleted_at"),
  ...audit(),
}, (t) => [index("contacts_ws_idx").on(t.workspaceId, t.createdAt), index("contacts_owner_idx").on(t.workspaceId, t.ownerId)]);

export const identities = pgTable("identities", {
  id: id(),
  workspaceId: tenant(),
  contactId: uuid("contact_id").notNull().references(() => contacts.id, { onDelete: "cascade" }),
  type: text("type").notNull(), // phone | email | fbp | device | wa_id | psid | anonymous
  valueNormalized: text("value_normalized").notNull(),
  ...audit(),
}, (t) => [uniqueIndex("identities_uq").on(t.workspaceId, t.type, t.valueNormalized)]);

/** CDP-002: merges are logged and reversible */
export const mergeLogs = pgTable("merge_logs", {
  id: id(),
  workspaceId: tenant(),
  survivorId: uuid("survivor_id").notNull(),
  mergedId: uuid("merged_id").notNull(),
  reason: text("reason").notNull(),
  snapshot: jsonb("snapshot").notNull(), // merged contact + moved row ids, for undo
  undoneAt: ts("undone_at"),
  ...audit(),
});

export const events = pgTable("events", {
  id: id(),
  workspaceId: tenant(),
  contactId: uuid("contact_id"),
  anonymousId: text("anonymous_id"),
  name: text("name").notNull(),
  properties: jsonb("properties").$type<Record<string, unknown>>().notNull().default({}),
  source: text("source").notNull().default("api"),
  occurredAt: ts("occurred_at").notNull().defaultNow(),
  createdAt: ts("created_at").notNull().defaultNow(),
}, (t) => [index("events_contact_idx").on(t.workspaceId, t.contactId, t.occurredAt), index("events_anon_idx").on(t.workspaceId, t.anonymousId)]);

export const consents = pgTable("consents", {
  id: id(),
  workspaceId: tenant(),
  contactId: uuid("contact_id").notNull().references(() => contacts.id, { onDelete: "cascade" }),
  channel: text("channel").notNull(), // email | sms | whatsapp | messenger | push
  status: text("status").notNull(), // opted_in | opted_out
  source: text("source").notNull(),
  capturedAt: ts("captured_at").notNull().defaultNow(),
  ...audit(),
}, (t) => [index("consents_contact_idx").on(t.workspaceId, t.contactId, t.channel)]);

export const customFieldDefs = pgTable("custom_field_defs", {
  id: id(),
  workspaceId: tenant(),
  objectType: text("object_type").notNull().default("contact"),
  key: text("key").notNull(),
  label: text("label").notNull(),
  type: text("type").notNull(), // text | number | date | dropdown | multiselect
  options: text("options").array().notNull().default(sql`'{}'::text[]`),
  ...audit(),
}, (t) => [uniqueIndex("cfd_uq").on(t.workspaceId, t.objectType, t.key)]);

/** CDP-007: custom objects (Property, Unit, Booking…) */
export const customObjectDefs = pgTable("custom_object_defs", {
  id: id(),
  workspaceId: tenant(),
  key: text("key").notNull(),
  label: text("label").notNull(),
  fields: jsonb("fields").$type<{ key: string; label: string; type: string; options?: string[] }[]>().notNull(),
  ...audit(),
}, (t) => [uniqueIndex("cod_uq").on(t.workspaceId, t.key)]);

export const customObjectRecords = pgTable("custom_object_records", {
  id: id(),
  workspaceId: tenant(),
  objectDefId: uuid("object_def_id").notNull().references(() => customObjectDefs.id, { onDelete: "cascade" }),
  contactId: uuid("contact_id").references(() => contacts.id, { onDelete: "set null" }),
  data: jsonb("data").$type<Record<string, unknown>>().notNull().default({}),
  ...audit(),
});

export const segments = pgTable("segments", {
  id: id(),
  workspaceId: tenant(),
  name: text("name").notNull(),
  definition: jsonb("definition").$type<SegmentDefinition>().notNull(),
  memberCount: integer("member_count").notNull().default(0),
  evaluatedAt: ts("evaluated_at"),
  audienceSync: jsonb("audience_sync").$type<{ meta?: boolean; google?: boolean; lastSyncAt?: string }>().notNull().default({}),
  ...audit(),
});

export const leadSources = pgTable("lead_sources", {
  id: id(),
  workspaceId: tenant(),
  contactId: uuid("contact_id").notNull().references(() => contacts.id, { onDelete: "cascade" }),
  dealId: uuid("deal_id"),
  channel: text("channel").notNull(), // meta_lead_ad | google_lead_form | web_form | whatsapp | messenger | api | call | import | tiktok | linkedin
  campaignId: text("campaign_id"),
  adsetId: text("adset_id"),
  adId: text("ad_id"),
  utmSource: text("utm_source"),
  utmMedium: text("utm_medium"),
  utmCampaign: text("utm_campaign"),
  utmTerm: text("utm_term"),
  utmContent: text("utm_content"),
  fbclid: text("fbclid"),
  gclid: text("gclid"),
  landingUrl: text("landing_url"),
  formId: uuid("form_id"),
  capturedAt: ts("captured_at").notNull().defaultNow(),
  ...audit(),
}, (t) => [index("lead_sources_contact_idx").on(t.workspaceId, t.contactId)]);

/* ---------------- Lead management ---------------- */

export const pipelines = pgTable("pipelines", {
  id: id(),
  workspaceId: tenant(),
  name: text("name").notNull(),
  isDefault: boolean("is_default").notNull().default(false),
  stages: jsonb("stages").$type<PipelineStage[]>().notNull(),
  slaMinutes: integer("sla_minutes").notNull().default(5),
  slaAction: text("sla_action").notNull().default("alert"), // alert | reassign
  ...audit(),
});

export const deals = pgTable("deals", {
  id: id(),
  workspaceId: tenant(),
  contactId: uuid("contact_id").notNull().references(() => contacts.id, { onDelete: "cascade" }),
  pipelineId: uuid("pipeline_id").notNull().references(() => pipelines.id),
  stageId: text("stage_id").notNull(),
  title: text("title").notNull(),
  value: bigint("value", { mode: "number" }).notNull().default(0),
  currency: text("currency").notNull(),
  ownerId: uuid("owner_id"),
  project: text("project"),
  lostReason: text("lost_reason"),
  wonAt: ts("won_at"),
  lostAt: ts("lost_at"),
  stageChangedAt: ts("stage_changed_at").notNull().defaultNow(),
  position: real("position").notNull().default(0),
  slaDueAt: ts("sla_due_at"),
  slaBreachedAt: ts("sla_breached_at"),
  ...audit(),
}, (t) => [index("deals_ws_stage_idx").on(t.workspaceId, t.pipelineId, t.stageId)]);

export const routingRules = pgTable("routing_rules", {
  id: id(),
  workspaceId: tenant(),
  name: text("name").notNull(),
  priority: integer("priority").notNull().default(100),
  strategy: text("strategy").notNull(), // round_robin | source | project | territory | workload
  match: jsonb("match").$type<{ source?: string; project?: string; territory?: string }>().notNull().default({}),
  userIds: uuid("user_ids").array().notNull().default(sql`'{}'::uuid[]`),
  cursor: integer("cursor").notNull().default(0),
  active: boolean("active").notNull().default(true),
  ...audit(),
});

export const activities = pgTable("activities", {
  id: id(),
  workspaceId: tenant(),
  contactId: uuid("contact_id").references(() => contacts.id, { onDelete: "cascade" }),
  dealId: uuid("deal_id"),
  userId: uuid("user_id"),
  type: text("type").notNull(), // call | note | meeting | visit | task | email | whatsapp | system | ai_summary
  title: text("title").notNull(),
  body: text("body"),
  dueAt: ts("due_at"),
  completedAt: ts("completed_at"),
  outcome: text("outcome"),
  durationSec: integer("duration_sec"),
  recordingUrl: text("recording_url"),
  calendarEventId: text("calendar_event_id"),
  reminderSentAt: ts("reminder_sent_at"),
  ...audit(),
}, (t) => [index("activities_contact_idx").on(t.workspaceId, t.contactId), index("activities_due_idx").on(t.workspaceId, t.userId, t.dueAt)]);

/* ---------------- Messaging ---------------- */

export const conversations = pgTable("conversations", {
  id: id(),
  workspaceId: tenant(),
  contactId: uuid("contact_id").notNull().references(() => contacts.id, { onDelete: "cascade" }),
  channel: text("channel").notNull(), // whatsapp | email | sms | messenger | instagram
  status: text("status").notNull().default("open"), // open | pending | closed
  assigneeId: uuid("assignee_id"),
  lastMessageAt: ts("last_message_at").notNull().defaultNow(),
  unread: integer("unread").notNull().default(0),
  aiAgentActive: boolean("ai_agent_active").notNull().default(false),
  /* Module 11 (SOC) — social inbox */
  kind: text("kind").notNull().default("dm"), // dm | comment_thread | review
  socialAccountId: uuid("social_account_id"),
  socialObjectId: uuid("social_object_id"),
  externalThreadId: text("external_thread_id"),
  priority: text("priority").notNull().default("normal"), // low | normal | high | urgent
  sentiment: text("sentiment"), // positive | neutral | negative
  intent: text("intent"),
  tags: text("tags").array().notNull().default(sql`'{}'::text[]`),
  slaDueAt: ts("sla_due_at"),
  slaBreachedAt: ts("sla_breached_at"),
  firstResponseAt: ts("first_response_at"),
  resolvedAt: ts("resolved_at"),
  lastInboundAt: ts("last_inbound_at"),
  snoozedUntil: ts("snoozed_until"),
  lockedByUserId: uuid("locked_by_user_id"),
  lockedUntil: ts("locked_until"),
  handledBy: text("handled_by"), // human | rule | ai — who sent the first response (SOC-083)
  ...audit(),
}, (t) => [index("conv_ws_idx").on(t.workspaceId, t.lastMessageAt), uniqueIndex("conv_ext_thread_uq").on(t.workspaceId, t.channel, t.externalThreadId)]);

export const messages = pgTable("messages", {
  id: id(),
  workspaceId: tenant(),
  conversationId: uuid("conversation_id").notNull().references(() => conversations.id, { onDelete: "cascade" }),
  direction: text("direction").notNull(), // in | out | note
  channel: text("channel").notNull(),
  templateId: uuid("template_id"),
  subject: text("subject"),
  body: text("body").notNull(),
  media: jsonb("media").$type<{ url: string; type: string }[]>().notNull().default([]),
  status: text("status").notNull().default("queued"), // queued | sent | delivered | read | failed | received | blocked
  error: text("error"),
  providerMessageId: text("provider_message_id"),
  senderId: uuid("sender_id"),
  broadcastId: uuid("broadcast_id"),
  openedAt: ts("opened_at"),
  clickedAt: ts("clicked_at"),
  ...audit(),
}, (t) => [index("messages_conv_idx").on(t.conversationId, t.createdAt), index("messages_provider_idx").on(t.providerMessageId)]);

export const templates = pgTable("templates", {
  id: id(),
  workspaceId: tenant(),
  channel: text("channel").notNull(),
  name: text("name").notNull(),
  language: text("language").notNull().default("en"),
  subject: text("subject"),
  body: text("body").notNull(),
  variables: text("variables").array().notNull().default(sql`'{}'::text[]`),
  providerStatus: text("provider_status").notNull().default("draft"), // draft | pending | approved | rejected
  category: text("category").notNull().default("marketing"),
  ...audit(),
});

export const cannedReplies = pgTable("canned_replies", {
  id: id(),
  workspaceId: tenant(),
  shortcut: text("shortcut").notNull(),
  body: text("body").notNull(),
  /* saved replies (SOC-024) extend canned replies */
  title: text("title"),
  variables: text("variables").array().notNull().default(sql`'{}'::text[]`),
  channels: text("channels").array().notNull().default(sql`'{}'::text[]`), // empty = all channels
  tags: text("tags").array().notNull().default(sql`'{}'::text[]`),
  language: text("language").notNull().default("en"),
  ...audit(),
});

export const broadcasts = pgTable("broadcasts", {
  id: id(),
  workspaceId: tenant(),
  name: text("name").notNull(),
  channel: text("channel").notNull(),
  segmentId: uuid("segment_id"),
  templateId: uuid("template_id"),
  body: text("body"),
  subject: text("subject"),
  scheduledAt: ts("scheduled_at"),
  throttlePerMinute: integer("throttle_per_minute").notNull().default(60),
  status: text("status").notNull().default("draft"), // draft | scheduled | sending | sent | cancelled
  stats: jsonb("stats").$type<{ targeted?: number; sent?: number; skipped?: number; failed?: number }>().notNull().default({}),
  cursor: integer("cursor").notNull().default(0),
  ...audit(),
});

/* ---------------- Journeys ---------------- */

export const journeys = pgTable("journeys", {
  id: id(),
  workspaceId: tenant(),
  name: text("name").notNull(),
  status: text("status").notNull().default("draft"), // draft | live | paused | archived
  version: integer("version").notNull().default(1),
  trigger: jsonb("trigger").$type<JourneyTrigger>().notNull(),
  graph: jsonb("graph").$type<JourneyGraph>().notNull(),
  goal: jsonb("goal").$type<JourneyGoal | null>(),
  stats: jsonb("stats").$type<Record<string, { entered: number; completed: number; failed: number }>>().notNull().default({}),
  ...audit(),
});

/** FLOW-004: published versions are immutable; runs pin to a version */
export const journeyVersions = pgTable("journey_versions", {
  id: id(),
  workspaceId: tenant(),
  journeyId: uuid("journey_id").notNull().references(() => journeys.id, { onDelete: "cascade" }),
  version: integer("version").notNull(),
  trigger: jsonb("trigger").$type<JourneyTrigger>().notNull(),
  graph: jsonb("graph").$type<JourneyGraph>().notNull(),
  goal: jsonb("goal").$type<JourneyGoal | null>(),
  ...audit(),
}, (t) => [uniqueIndex("jv_uq").on(t.journeyId, t.version)]);

export const journeyRuns = pgTable("journey_runs", {
  id: id(),
  workspaceId: tenant(),
  journeyId: uuid("journey_id").notNull().references(() => journeys.id, { onDelete: "cascade" }),
  version: integer("version").notNull(),
  contactId: uuid("contact_id").notNull().references(() => contacts.id, { onDelete: "cascade" }),
  currentStep: text("current_step"),
  status: text("status").notNull().default("active"), // active | waiting | completed | failed | exited
  resumeAt: ts("resume_at"),
  log: jsonb("log").$type<{ step: string; at: string; status: string; detail?: string }[]>().notNull().default([]),
  ...audit(),
}, (t) => [index("runs_resume_idx").on(t.status, t.resumeAt)]);

/* ---------------- Integrations ---------------- */

export const integrations = pgTable("integrations", {
  id: id(),
  workspaceId: tenant(),
  provider: text("provider").notNull(),
  accountRef: text("account_ref"),
  displayName: text("display_name"),
  scopes: text("scopes").array().notNull().default(sql`'{}'::text[]`),
  /** reference to the encrypted secret in `secrets` (vault); tokens never live in this row */
  tokenRef: uuid("token_ref"),
  config: jsonb("config").$type<Record<string, unknown>>().notNull().default({}),
  fieldMapping: jsonb("field_mapping").$type<Record<string, string>>().notNull().default({}),
  status: text("status").notNull().default("connected"), // connected | error | expired | disconnected
  mode: text("mode").notNull().default("sandbox"), // live | sandbox
  lastSyncAt: ts("last_sync_at"),
  lastError: text("last_error"),
  expiresAt: ts("expires_at"),
  ...audit(),
});

/** Encrypted secret store (AES-256-GCM). Swap for AWS Secrets Manager / Vault via SECRETS_DRIVER. */
export const secrets = pgTable("secrets", {
  id: id(),
  workspaceId: uuid("workspace_id"),
  ciphertext: text("ciphertext").notNull(),
  createdAt: ts("created_at").notNull().defaultNow(),
});

export const integrationLogs = pgTable("integration_logs", {
  id: id(),
  workspaceId: tenant(),
  integrationId: uuid("integration_id"),
  provider: text("provider").notNull(),
  direction: text("direction").notNull(), // in | out
  operation: text("operation").notNull(),
  status: text("status").notNull(), // ok | error
  summary: text("summary"),
  at: ts("at").notNull().defaultNow(),
}, (t) => [index("intlog_ws_idx").on(t.workspaceId, t.at)]);

export const webhookSubscriptions = pgTable("webhook_subscriptions", {
  id: id(),
  workspaceId: tenant(),
  url: text("url").notNull(),
  events: text("events").array().notNull(),
  secret: text("secret").notNull(),
  status: text("status").notNull().default("active"),
  ...audit(),
});

export const webhookDeliveries = pgTable("webhook_deliveries", {
  id: id(),
  workspaceId: tenant(),
  subscriptionId: uuid("subscription_id").notNull().references(() => webhookSubscriptions.id, { onDelete: "cascade" }),
  eventId: uuid("event_id").notNull(),
  eventType: text("event_type").notNull(),
  payload: jsonb("payload").notNull(),
  status: text("status").notNull().default("pending"), // pending | delivered | failed | dead
  attempts: integer("attempts").notNull().default(0),
  responseCode: integer("response_code"),
  nextAttemptAt: ts("next_attempt_at"),
  ...audit(),
});

/* ---------------- Ads ---------------- */

export const adAccounts = pgTable("ad_accounts", {
  id: id(),
  workspaceId: tenant(),
  integrationId: uuid("integration_id"),
  provider: text("provider").notNull(), // meta | google | tiktok | linkedin
  externalId: text("external_id").notNull(),
  name: text("name").notNull(),
  currency: text("currency").notNull(),
  timezone: text("timezone").notNull(),
  status: text("status").notNull().default("active"),
  monthlyBudget: bigint("monthly_budget", { mode: "number" }),
  pixelId: text("pixel_id"),
  ...audit(),
});

export const campaigns = pgTable("campaigns", {
  id: id(),
  workspaceId: tenant(),
  adAccountId: uuid("ad_account_id").notNull().references(() => adAccounts.id, { onDelete: "cascade" }),
  provider: text("provider").notNull(),
  externalId: text("external_id").notNull(),
  name: text("name").notNull(),
  status: text("status").notNull().default("active"),
  budget: bigint("budget", { mode: "number" }),
  objective: text("objective"),
  ...audit(),
});

export const adSets = pgTable("ad_sets", {
  id: id(),
  workspaceId: tenant(),
  campaignId: uuid("campaign_id").notNull().references(() => campaigns.id, { onDelete: "cascade" }),
  provider: text("provider").notNull(),
  externalId: text("external_id").notNull(),
  name: text("name").notNull(),
  status: text("status").notNull().default("active"),
  budget: bigint("budget", { mode: "number" }),
  ...audit(),
});

export const ads = pgTable("ads", {
  id: id(),
  workspaceId: tenant(),
  adSetId: uuid("ad_set_id").notNull().references(() => adSets.id, { onDelete: "cascade" }),
  provider: text("provider").notNull(),
  externalId: text("external_id").notNull(),
  name: text("name").notNull(),
  status: text("status").notNull().default("active"),
  ...audit(),
});

export const adMetricsDaily = pgTable("ad_metrics_daily", {
  id: id(),
  workspaceId: tenant(),
  date: date("date", { mode: "string" }).notNull(),
  adId: uuid("ad_id").notNull().references(() => ads.id, { onDelete: "cascade" }),
  spend: bigint("spend", { mode: "number" }).notNull().default(0), // minor units, account currency
  impressions: integer("impressions").notNull().default(0),
  clicks: integer("clicks").notNull().default(0),
  leads: integer("leads").notNull().default(0),
  conversions: integer("conversions").notNull().default(0),
}, (t) => [uniqueIndex("amd_uq").on(t.adId, t.date), index("amd_ws_date_idx").on(t.workspaceId, t.date)]);

export const conversionSyncs = pgTable("conversion_syncs", {
  id: id(),
  workspaceId: tenant(),
  dealId: uuid("deal_id"),
  contactId: uuid("contact_id"),
  provider: text("provider").notNull(), // meta | google | tiktok | linkedin
  eventName: text("event_name").notNull(), // Lead | Qualified | SiteVisit | Won
  eventId: text("event_id").notNull(), // dedupe key
  value: bigint("value", { mode: "number" }),
  currency: text("currency"),
  payload: jsonb("payload"),
  response: jsonb("response"),
  status: text("status").notNull().default("pending"), // pending | sent | failed | skipped
  sentAt: ts("sent_at"),
  ...audit(),
}, (t) => [uniqueIndex("convsync_uq").on(t.workspaceId, t.provider, t.eventId)]);

/* ---------------- Forms, pages, content ---------------- */

export const forms = pgTable("forms", {
  id: id(),
  workspaceId: tenant(),
  type: text("type").notNull(), // form | page
  name: text("name").notNull(),
  slug: text("slug").notNull(),
  schema: jsonb("schema").$type<FormSchema | PageSchema>().notNull(),
  variants: jsonb("variants").$type<PageVariant[]>().notNull().default([]),
  domain: text("domain"),
  publishedVersion: integer("published_version").notNull().default(0),
  status: text("status").notNull().default("draft"),
  pixels: jsonb("pixels").$type<{ metaPixelId?: string; ga4Id?: string; gtmId?: string }>().notNull().default({}),
  stats: jsonb("stats").$type<Record<string, { views: number; submits: number }>>().notNull().default({}),
  ...audit(),
}, (t) => [uniqueIndex("forms_slug_uq").on(t.workspaceId, t.slug)]);

export const submissions = pgTable("submissions", {
  id: id(),
  workspaceId: tenant(),
  formId: uuid("form_id").notNull().references(() => forms.id, { onDelete: "cascade" }),
  contactId: uuid("contact_id"),
  variant: text("variant"),
  data: jsonb("data").$type<Record<string, unknown>>().notNull(),
  meta: jsonb("meta").$type<Record<string, unknown>>().notNull().default({}),
  ...audit(),
});

export const contentPosts = pgTable("content_posts", {
  id: id(),
  workspaceId: tenant(),
  channels: text("channels").array().notNull(),
  campaign: text("campaign"),
  body: text("body").notNull(),
  media: jsonb("media").$type<{ assetId?: string; url: string; type: string }[]>().notNull().default([]),
  status: text("status").notNull().default("draft"), // draft | in_review | approved | scheduled | published | failed
  scheduledAt: ts("scheduled_at"),
  publishedAt: ts("published_at"),
  externalPostIds: jsonb("external_post_ids").$type<Record<string, string>>().notNull().default({}),
  approverId: uuid("approver_id"),
  approvalToken: text("approval_token"),
  approvalNote: text("approval_note"),
  metrics: jsonb("metrics").$type<{ reach?: number; engagement?: number; likes?: number; comments?: number; shares?: number }>().notNull().default({}),
  ...audit(),
});

export const brandKits = pgTable("brand_kits", {
  id: id(),
  workspaceId: tenant(),
  name: text("name").notNull(),
  logos: text("logos").array().notNull().default(sql`'{}'::text[]`),
  colors: text("colors").array().notNull().default(sql`'{}'::text[]`),
  fonts: text("fonts").array().notNull().default(sql`'{}'::text[]`),
  voice: text("voice"),
  ...audit(),
});

export const assets = pgTable("assets", {
  id: id(),
  workspaceId: tenant(),
  type: text("type").notNull(), // image | video | document | logo
  name: text("name").notNull(),
  url: text("url").notNull(),
  folder: text("folder").notNull().default("General"),
  tags: text("tags").array().notNull().default(sql`'{}'::text[]`),
  brandKitId: uuid("brand_kit_id"),
  sizeBytes: integer("size_bytes"),
  ...audit(),
});

/* ---------------- Analytics & reports ---------------- */

export const savedReports = pgTable("saved_reports", {
  id: id(),
  workspaceId: tenant(),
  name: text("name").notNull(),
  config: jsonb("config").$type<ReportConfig>().notNull(),
  schedule: text("schedule"), // null | weekly_mon | monthly_1
  recipients: text("recipients").array().notNull().default(sql`'{}'::text[]`),
  shareToken: text("share_token"),
  lastSentAt: ts("last_sent_at"),
  ...audit(),
});

/* ---------------- AI ---------------- */

export const aiActions = pgTable("ai_actions", {
  id: id(),
  workspaceId: tenant(),
  agent: text("agent").notNull(),
  kind: text("kind").notNull(), // pause_ad | resume_ad | change_budget | launch_journey | send_broadcast
  proposedAction: jsonb("proposed_action").$type<Record<string, unknown>>().notNull(),
  reasoning: text("reasoning"),
  expectedImpact: text("expected_impact"),
  status: text("status").notNull().default("proposed"), // proposed | approved | rejected | executed | failed
  approverId: uuid("approver_id"),
  result: jsonb("result"),
  ...audit(),
});

export const aiAutoApproveRules = pgTable("ai_auto_approve_rules", {
  id: id(),
  workspaceId: tenant(),
  kind: text("kind").notNull(),
  maxBudgetChangePct: integer("max_budget_change_pct").notNull().default(0),
  maxDailySpend: bigint("max_daily_spend", { mode: "number" }).notNull().default(0),
  active: boolean("active").notNull().default(true),
  ...audit(),
});

export const aiLogs = pgTable("ai_logs", {
  id: id(),
  workspaceId: tenant(),
  feature: text("feature").notNull(),
  model: text("model").notNull(),
  promptHash: text("prompt_hash").notNull(),
  prompt: text("prompt").notNull(),
  response: text("response"),
  toolCalls: jsonb("tool_calls"),
  inputTokens: integer("input_tokens").notNull().default(0),
  outputTokens: integer("output_tokens").notNull().default(0),
  credits: integer("credits").notNull().default(0),
  cached: boolean("cached").notNull().default(false),
  ...audit(),
}, (t) => [index("ailog_hash_idx").on(t.workspaceId, t.promptHash)]);

export const anomalies = pgTable("anomalies", {
  id: id(),
  workspaceId: tenant(),
  metric: text("metric").notNull(),
  objectType: text("object_type").notNull(),
  objectId: text("object_id"),
  objectName: text("object_name"),
  baseline: real("baseline").notNull(),
  current: real("current").notNull(),
  changePct: real("change_pct").notNull(),
  message: text("message").notNull(),
  acknowledgedAt: ts("acknowledged_at"),
  ...audit(),
});

/* ---------------- Billing & usage ---------------- */

export const usageRecords = pgTable("usage_records", {
  id: id(),
  workspaceId: tenant(),
  meter: text("meter").notNull(), // sms | whatsapp | ai_credits | contacts | email
  quantity: integer("quantity").notNull(),
  period: text("period").notNull(), // YYYY-MM
  ...audit(),
}, (t) => [index("usage_ws_period_idx").on(t.workspaceId, t.period, t.meter)]);

export const invoices = pgTable("invoices", {
  id: id(),
  workspaceId: tenant(),
  period: text("period").notNull(),
  provider: text("provider").notNull(), // stripe | sslcommerz | bkash
  amount: bigint("amount", { mode: "number" }).notNull(),
  currency: text("currency").notNull(),
  lines: jsonb("lines").$type<{ label: string; quantity: number; unit: number; total: number }[]>().notNull(),
  status: text("status").notNull().default("open"), // open | paid | void
  externalId: text("external_id"),
  ...audit(),
});

/* ---------------- Platform plumbing ---------------- */

export const notifications = pgTable("notifications", {
  id: id(),
  workspaceId: tenant(),
  userId: uuid("user_id"),
  kind: text("kind").notNull(),
  title: text("title").notNull(),
  body: text("body"),
  link: text("link"),
  readAt: ts("read_at"),
  ...audit(),
}, (t) => [index("notif_user_idx").on(t.workspaceId, t.userId, t.createdAt)]);

/** Durable job queue (BullMQ-equivalent backed by Postgres, drained by Vercel Cron + after()) */
export const jobs = pgTable("jobs", {
  id: id(),
  workspaceId: uuid("workspace_id"),
  type: text("type").notNull(),
  payload: jsonb("payload").$type<Record<string, unknown>>().notNull(),
  status: text("status").notNull().default("queued"), // queued | running | done | failed | dead
  attempts: integer("attempts").notNull().default(0),
  maxAttempts: integer("max_attempts").notNull().default(8),
  runAt: ts("run_at").notNull().defaultNow(),
  lockedAt: ts("locked_at"),
  lastError: text("last_error"),
  idempotencyKey: text("idempotency_key"),
  createdAt: ts("created_at").notNull().defaultNow(),
  updatedAt: ts("updated_at").notNull().defaultNow(),
}, (t) => [index("jobs_pick_idx").on(t.status, t.runAt), uniqueIndex("jobs_idem_uq").on(t.idempotencyKey)]);

export const idempotencyKeys = pgTable("idempotency_keys", {
  key: text("key").primaryKey(), // workspace:key
  response: jsonb("response").notNull(),
  statusCode: integer("status_code").notNull(),
  createdAt: ts("created_at").notNull().defaultNow(),
});

export const rateLimits = pgTable("rate_limits", {
  bucket: text("bucket").primaryKey(),
  count: integer("count").notNull(),
  windowStart: ts("window_start").notNull(),
});

/* ---------------- Module 11: social inbox & engagement (SOC) ---------------- */

/** One per connected Facebook Page, Instagram account, TikTok account, LinkedIn org, YouTube channel or GBP location */
export const socialAccounts = pgTable("social_accounts", {
  id: id(),
  workspaceId: tenant(),
  integrationId: uuid("integration_id"),
  channelFamily: text("channel_family").notNull(), // meta | tiktok | linkedin | youtube | google_business
  platform: text("platform").notNull(), // facebook | instagram | tiktok | linkedin | youtube | google_business
  externalAccountId: text("external_account_id").notNull(),
  name: text("name").notNull(),
  avatarUrl: text("avatar_url"),
  status: text("status").notNull().default("inactive"), // active | inactive | disconnected | error
  capabilities: jsonb("capabilities").$type<SocialCapabilities>().notNull().default({}),
  webhookSubscribed: boolean("webhook_subscribed").notNull().default(false),
  lastEventAt: ts("last_event_at"),
  lastPolledAt: ts("last_polled_at"),
  pollCursor: text("poll_cursor"),
  backfill: jsonb("backfill").$type<{ status?: string; done?: number; total?: number; finishedAt?: string; error?: string }>().notNull().default({}),
  lastError: text("last_error"),
  ...audit(),
}, (t) => [uniqueIndex("social_accounts_uq").on(t.workspaceId, t.platform, t.externalAccountId), index("social_accounts_ext_idx").on(t.externalAccountId)]);

/** Posts, reels, videos, ads and stories that receive comments */
export const socialObjects = pgTable("social_objects", {
  id: id(),
  workspaceId: tenant(),
  socialAccountId: uuid("social_account_id").notNull().references(() => socialAccounts.id, { onDelete: "cascade" }),
  type: text("type").notNull(), // post | reel | video | ad | story | location
  externalId: text("external_id").notNull(),
  permalink: text("permalink"),
  thumbnailUrl: text("thumbnail_url"),
  captionExcerpt: text("caption_excerpt"),
  adId: uuid("ad_id"), // fk → ads (internal)
  externalAdId: text("external_ad_id"),
  campaignId: uuid("campaign_id"),
  campaignName: text("campaign_name"),
  publishedAt: ts("published_at"),
  ...audit(),
}, (t) => [uniqueIndex("social_objects_uq").on(t.socialAccountId, t.externalId)]);

export const comments = pgTable("comments", {
  id: id(),
  workspaceId: tenant(),
  conversationId: uuid("conversation_id").notNull().references(() => conversations.id, { onDelete: "cascade" }),
  socialObjectId: uuid("social_object_id"),
  channel: text("channel").notNull(),
  externalCommentId: text("external_comment_id").notNull(),
  parentExternalCommentId: text("parent_external_comment_id"),
  authorExternalId: text("author_external_id"),
  authorName: text("author_name"),
  authorHandle: text("author_handle"),
  contactId: uuid("contact_id"),
  direction: text("direction").notNull(), // inbound | outbound
  body: text("body").notNull(),
  editHistory: jsonb("edit_history").$type<{ body: string; at: string }[]>().notNull().default([]),
  media: jsonb("media").$type<{ url: string; type: string }[]>().notNull().default([]),
  isHidden: boolean("is_hidden").notNull().default(false),
  hiddenReason: text("hidden_reason"),
  hiddenBy: text("hidden_by"), // user:<id> | rule:<id> | ai
  isDeleted: boolean("is_deleted").notNull().default(false),
  likedByPage: boolean("liked_by_page").notNull().default(false),
  likeCount: integer("like_count").notNull().default(0),
  sentiment: text("sentiment"),
  intent: text("intent"),
  language: text("language"),
  toxicity: real("toxicity"),
  externalCreatedAt: ts("external_created_at").notNull().defaultNow(),
  sentByUserId: uuid("sent_by_user_id"),
  sentByAi: boolean("sent_by_ai").notNull().default(false),
  sentByRuleId: uuid("sent_by_rule_id"),
  providerStatus: text("provider_status").notNull().default("received"), // received | queued | sent | failed
  providerError: text("provider_error"),
  ...audit(),
}, (t) => [uniqueIndex("comments_ext_uq").on(t.workspaceId, t.channel, t.externalCommentId), index("comments_conv_idx").on(t.conversationId, t.externalCreatedAt)]);

export const reviews = pgTable("reviews", {
  id: id(),
  workspaceId: tenant(),
  conversationId: uuid("conversation_id").notNull().references(() => conversations.id, { onDelete: "cascade" }),
  socialAccountId: uuid("social_account_id").notNull().references(() => socialAccounts.id, { onDelete: "cascade" }),
  externalReviewId: text("external_review_id").notNull(),
  reviewerName: text("reviewer_name"),
  rating: integer("rating").notNull(),
  body: text("body"),
  language: text("language"),
  externalCreatedAt: ts("external_created_at").notNull().defaultNow(),
  replyBody: text("reply_body"),
  replyStatus: text("reply_status").notNull().default("none"), // none | draft | pending_approval | published | failed
  repliedAt: ts("replied_at"),
  repliedByUserId: uuid("replied_by_user_id"),
  repliedByAi: boolean("replied_by_ai").notNull().default(false),
  ...audit(),
}, (t) => [uniqueIndex("reviews_ext_uq").on(t.socialAccountId, t.externalReviewId)]);

/** Decides free-form vs template-only sends (SOC-034) and private-reply eligibility (SOC-031) */
export const messagingWindows = pgTable("messaging_windows", {
  id: id(),
  workspaceId: tenant(),
  contactId: uuid("contact_id").notNull().references(() => contacts.id, { onDelete: "cascade" }),
  channel: text("channel").notNull(),
  socialAccountId: uuid("social_account_id"),
  lastInboundAt: ts("last_inbound_at").notNull(),
  windowExpiresAt: ts("window_expires_at").notNull(),
  privateReplyAvailableUntil: ts("private_reply_available_until"),
  ...audit(),
}, (t) => [uniqueIndex("msg_windows_uq").on(t.workspaceId, t.contactId, t.channel)]);

export const engagementRules = pgTable("engagement_rules", {
  id: id(),
  workspaceId: tenant(),
  name: text("name").notNull(),
  type: text("type").notNull(), // auto_reply | comment_to_dm | moderation | routing | ai_autopilot | alert
  channels: text("channels").array().notNull().default(sql`'{}'::text[]`), // empty = all
  socialAccountIds: uuid("social_account_ids").array().notNull().default(sql`'{}'::uuid[]`),
  socialObjectIds: uuid("social_object_ids").array().notNull().default(sql`'{}'::uuid[]`),
  trigger: text("trigger").notNull().default("new_comment"), // new_comment | new_dm | new_review | any
  conditions: jsonb("conditions").$type<RuleConditions>().notNull().default({}),
  actions: jsonb("actions").$type<RuleAction[]>().notNull().default([]),
  priority: integer("priority").notNull().default(100),
  stopProcessing: boolean("stop_processing").notNull().default(false),
  isActive: boolean("is_active").notNull().default(true),
  schedule: jsonb("schedule").$type<RuleSchedule>().notNull().default({}),
  rateLimit: jsonb("rate_limit").$type<{ perMinute?: number; oncePerUserPerObject?: boolean; oncePerUserPerDay?: boolean }>().notNull().default({}),
  stats: jsonb("stats").$type<{ fires?: number; replies?: number; leads?: number; hides?: number; lastFiredAt?: string; rotation?: number }>().notNull().default({}),
  ...audit(),
}, (t) => [index("engagement_rules_ws_idx").on(t.workspaceId, t.priority)]);

/** Each time a rule fires (rate limits, once-per-user, rule analytics — SOC-054/057) */
export const ruleFirings = pgTable("rule_firings", {
  id: id(),
  workspaceId: tenant(),
  ruleId: uuid("rule_id").notNull().references(() => engagementRules.id, { onDelete: "cascade" }),
  conversationId: uuid("conversation_id"),
  authorExternalId: text("author_external_id"),
  socialObjectId: uuid("social_object_id"),
  actions: jsonb("actions").$type<{ type: string; ok: boolean; detail?: string }[]>().notNull().default([]),
  ...audit(),
}, (t) => [index("rule_firings_idx").on(t.ruleId, t.createdAt)]);

export const socialBlocklist = pgTable("social_blocklist", {
  id: id(),
  workspaceId: tenant(),
  platform: text("platform").notNull(),
  authorExternalId: text("author_external_id").notNull(),
  authorName: text("author_name"),
  reason: text("reason"),
  ...audit(),
}, (t) => [uniqueIndex("social_blocklist_uq").on(t.workspaceId, t.platform, t.authorExternalId)]);

/** Moderation log with undo (SOC-063) */
export const moderationEvents = pgTable("moderation_events", {
  id: id(),
  workspaceId: tenant(),
  commentId: uuid("comment_id").notNull().references(() => comments.id, { onDelete: "cascade" }),
  action: text("action").notNull(), // hide | unhide | delete | mark_spam
  reason: text("reason"),
  actorType: text("actor_type").notNull(), // user | rule | ai
  actorId: text("actor_id"),
  actorName: text("actor_name"),
  undoneAt: ts("undone_at"),
  ...audit(),
}, (t) => [index("moderation_events_ws_idx").on(t.workspaceId, t.createdAt)]);

/** AI knowledge base (SOC-AI-003) */
export const knowledgeEntries = pgTable("knowledge_entries", {
  id: id(),
  workspaceId: tenant(),
  question: text("question").notNull(),
  answer: text("answer").notNull(),
  scope: text("scope"), // project or page name; null = whole workspace
  socialAccountId: uuid("social_account_id"),
  language: text("language").notNull().default("en"),
  tags: text("tags").array().notNull().default(sql`'{}'::text[]`),
  isActive: boolean("is_active").notNull().default(true),
  ...audit(),
});

export const engagementMetricsDaily = pgTable("engagement_metrics_daily", {
  id: id(),
  workspaceId: tenant(),
  date: date("date", { mode: "string" }).notNull(),
  socialAccountId: uuid("social_account_id"),
  channel: text("channel").notNull(),
  userId: uuid("user_id"),
  inboundCount: integer("inbound_count").notNull().default(0),
  repliedCount: integer("replied_count").notNull().default(0),
  medianFirstResponseS: integer("median_first_response_s"),
  p90FirstResponseS: integer("p90_first_response_s"),
  resolvedCount: integer("resolved_count").notNull().default(0),
  hiddenCount: integer("hidden_count").notNull().default(0),
  negativeCount: integer("negative_count").notNull().default(0),
  leadsCreated: integer("leads_created").notNull().default(0),
}, (t) => [index("eng_metrics_idx").on(t.workspaceId, t.date)]);

/* ---------------- JSON shapes ---------------- */
export type SocialCapabilities = { can_reply?: boolean; can_hide?: boolean; can_delete?: boolean; can_like?: boolean; can_private_reply?: boolean; can_dm?: boolean; can_reply_review?: boolean };
export type RuleConditions = {
  keywords?: string[]; keywordMode?: "any" | "all"; intents?: string[]; sentiments?: string[]; maxRating?: number; languages?: string[];
  firstMessageFromNewContact?: boolean; hasPhone?: boolean; hasLink?: boolean; profanity?: boolean; competitorNames?: string[]; contactField?: { field: string; value: string };
  volumeSpike?: { count: number; minutes: number };
};
export type RuleAction = { type: "public_reply" | "private_reply" | "hide" | "like" | "tag" | "assign" | "set_priority" | "create_lead" | "start_journey" | "notify" | "send_whatsapp_template" | "ai_reply" | "mark_spam" | "block_author"; config?: Record<string, unknown> };
export type RuleSchedule = { mode?: "always" | "in_hours" | "out_of_hours"; days?: number[]; start?: string; end?: string; timezone?: string };

export type Branding = { logoUrl?: string; primaryColor?: string; productName?: string; loginDomain?: string; hidePlatformBranding?: boolean };
export type WorkspaceSettings = {
  quietHours?: { start: string; end: string; enabled: boolean };
  frequencyCap?: { perDay: number; enabled: boolean };
  mfaRequired?: boolean;
  sessionTimeoutMinutes?: number;
  brandVoice?: string;
  attributionModel?: "first_touch" | "last_touch" | "linear" | "time_decay" | "position_based";
  pacingThresholdPct?: number;
  anomalyThresholdPct?: number;
  dataRegion?: string;
  aiCreditsMonthly?: number;
  defaultCountryCode?: string;
  security?: SecuritySettings;
  salesTargetQuarterly?: number; // minor units; dashboard target (auto-suggested when unset)
  industry?: string; // key of lib/industry.ts INDUSTRIES — drives AI prompts and labels
  visitLabel?: string; // optional rename of the booked step ("Site visit", "Appointment", "Test drive"…)
  social?: SocialSettings;
};
export type SecuritySettings = {
  allowedMfaMethods?: ("totp" | "email" | "sms" | "webauthn")[]; // empty/undefined = all
  ipAllowlist?: string[]; // IPv4/IPv6 addresses or IPv4 CIDR ranges; empty = any
  passwordMinLength?: number; // 10–64
  loginAlerts?: boolean; // email users on sign-in from a new device
  trustedDeviceDays?: number; // 0 disables "remember this device"
};
export type SocialSettings = {
  sla?: { dm?: number; comment?: number; review?: number }; // minutes (SOC-071)
  hours?: { days: number[]; start: string; end: string }; // business-hours calendar, workspace timezone
  escalation?: "notify" | "reassign"; // SOC-072
  featureFlags?: { tiktok?: boolean; linkedin?: boolean }; // SOC-007
  ai?: { autopilot?: boolean; threshold?: number; allowedIntents?: string[]; publicReplies?: boolean; languageMode?: "match" | "bangla" | "english"; banglishReply?: "banglish" | "bangla"; classify?: boolean };
  moderation?: { blockedWords?: string[]; competitorNames?: string[] };
  whatsappNumber?: string; // for Move to WhatsApp click-to-chat (SOC-035)
  spikeThreshold?: number; // comments per post in 30 min that trigger a volume alert (SOC-061)
};
export type PipelineStage = { id: string; name: string; order: number; probability: number; kind?: "open" | "won" | "lost"; conversionEvent?: string };
export type SegmentRule = { field: string; op: "eq" | "neq" | "contains" | "gt" | "lt" | "in" | "exists" | "not_exists" | "within_days"; value?: unknown };
export type SegmentDefinition = { match: "all" | "any"; rules: SegmentRule[] };
export type JourneyTrigger = { type: "contact_created" | "field_changed" | "stage_changed" | "form_submitted" | "event_received" | "tag_added" | "date_based" | "webhook" | "manual"; config?: Record<string, unknown> };
export type JourneyNode = { id: string; type: "trigger" | "action" | "condition" | "wait" | "split" | "goal" | "exit"; position: { x: number; y: number }; data: Record<string, unknown> };
export type JourneyEdge = { id: string; source: string; target: string; sourceHandle?: string | null; label?: string };
export type JourneyGraph = { nodes: JourneyNode[]; edges: JourneyEdge[] };
export type JourneyGoal = { type: "stage_reached" | "tag_added" | "event_received"; value: string };
export type FormField = { key: string; label: string; type: "text" | "email" | "phone" | "number" | "select" | "textarea" | "checkbox" | "hidden"; required?: boolean; options?: string[]; mapTo?: string };
export type FormSchema = { kind: "form"; title: string; description?: string; fields: FormField[]; submitLabel: string; successMessage: string; consent?: { channel: string; label: string }[]; captcha?: boolean; createDeal?: boolean; project?: string };
export type PageBlock = { id: string; type: "hero" | "features" | "text" | "image" | "form" | "cta" | "testimonial" | "faq" | "gallery"; props: Record<string, unknown> };
export type PageSchema = { kind: "page"; title: string; blocks: PageBlock[]; theme?: { accent?: string; dark?: boolean }; formId?: string; seo?: { title?: string; description?: string } };
export type PageVariant = { key: string; weight: number; blocks: PageBlock[] };
export type ReportConfig = { from?: string; to?: string; days?: number; sections: string[]; filters?: Record<string, string>; whiteLabel?: boolean; model?: string };
