import { z } from 'zod'

/**
 * CRM Overview API Schemas
 *
 * Request/response validation for /api/crm surface.
 * Covers recent activity feeds sourced from acq_deal_notes and deal
 * activity_log entries.
 *
 * The CrmActivityEntry discriminated union mirrors the CrmActivityEntry
 * interface defined in:
 *   packages/ui/src/features/acquisition/overview/hooks/useRecentCrmActivity.ts
 */

// ---------------------------------------------------------------------------
// Enum literals
// ---------------------------------------------------------------------------

export const CrmActivityKindSchema = z.enum(['note', 'stage_change', 'deal_created'])

// ---------------------------------------------------------------------------
// Activity entry shapes
// ---------------------------------------------------------------------------

/**
 * A single CRM activity entry (note, stage change, or deal creation).
 * Matches the CrmActivityEntry interface from useRecentCrmActivity.ts.
 */
export const RecentActivityEntrySchema = z.object({
  id: z.string(),
  kind: CrmActivityKindSchema,
  dealId: z.string(),
  occurredAt: z.string(),
  description: z.string(),
  contactName: z.string().nullable().optional(),
  companyName: z.string().nullable().optional(),
  stage: z.string().nullable().optional()
})

// ---------------------------------------------------------------------------
// Query schemas
// ---------------------------------------------------------------------------

export const GetRecentActivityQuerySchema = z
  .object({
    limit: z.coerce.number().int().min(1).max(100).default(20)
  })
  .strict()

// ---------------------------------------------------------------------------
// Response schemas (no .strict() — forward-compatible)
// ---------------------------------------------------------------------------

export const GetRecentActivityResponseSchema = z.object({
  entries: z.array(RecentActivityEntrySchema)
})

// ---------------------------------------------------------------------------
// Bundled export
// ---------------------------------------------------------------------------

export const CrmSchemas = {
  GetRecentActivityQuery: GetRecentActivityQuerySchema,
  RecentActivityEntry: RecentActivityEntrySchema,
  GetRecentActivityResponse: GetRecentActivityResponseSchema
}

// ---------------------------------------------------------------------------
// Inferred types
// ---------------------------------------------------------------------------

export type CrmActivityKind = z.infer<typeof CrmActivityKindSchema>
export type RecentActivityEntry = z.infer<typeof RecentActivityEntrySchema>
export type GetRecentActivityQuery = z.infer<typeof GetRecentActivityQuerySchema>
export type GetRecentActivityResponse = z.infer<typeof GetRecentActivityResponseSchema>
