import { z } from 'zod'
import {
  CompanyProcessingStateSchema,
  ContactProcessingStateSchema
} from '../../../../../business/acquisition/api-schemas'
import { EmailSchema } from '../../../../../platform/utils/validation'

// ============================================
// LIST SCHEMAS
// ============================================

export const CreateListInputSchema = z.object({
  name: z.string().min(1),
  description: z.string().optional(),
  buildTemplateId: z.string().trim().min(1).max(100).optional()
})

export const UpdateListInputSchema = z.object({
  id: z.string().uuid(),
  name: z.string().min(1).optional(),
  description: z.string().optional()
})

export const DeleteListInputSchema = z.object({
  id: z.string().uuid()
})

export const ListOutputSchema = z.object({
  id: z.string().uuid(),
  organizationId: z.string().uuid(),
  name: z.string(),
  description: z.string().nullable(),
  createdAt: z.string() // ISO date string
})

export const ListArrayOutputSchema = z.array(ListOutputSchema)

// ============================================
// COMPANY SCHEMAS
// ============================================

export const CreateCompanyInputSchema = z.object({
  name: z.string().min(1),
  domain: z.string().optional(),
  linkedinUrl: z.string().url().optional(),
  website: z.string().url().optional(),
  numEmployees: z.number().int().positive().optional(),
  foundedYear: z.number().int().min(1800).max(2100).optional(),
  locationCity: z.string().optional(),
  locationState: z.string().optional(),
  source: z.string().optional(),
  batchId: z.string().optional(),
  pipelineStatus: z.unknown().optional().describe('@deprecated Use processingState. Compatibility no-op.')
})

export const UpdateCompanyInputSchema = z.object({
  id: z.string().uuid(),
  name: z.string().min(1).optional(),
  domain: z.string().optional(),
  linkedinUrl: z.string().url().optional(),
  website: z.string().url().optional(),
  numEmployees: z.number().int().positive().optional(),
  foundedYear: z.number().int().min(1800).max(2100).optional(),
  locationCity: z.string().optional(),
  locationState: z.string().optional(),
  category: z.string().optional(),
  segment: z.string().optional(),
  processingState: CompanyProcessingStateSchema.optional(),
  pipelineStatus: z.unknown().optional().describe('@deprecated Use processingState. Compatibility no-op.'),
  enrichmentData: z.record(z.string(), z.unknown()).optional(),
  source: z.string().optional(),
  batchId: z.string().optional(),
  /** Track A: flat qualification score column (null until a scoring rubric is defined) */
  qualificationScore: z.number().nullable().optional(),
  /** Track A: flat qualification signals jsonb */
  qualificationSignals: z.record(z.string(), z.unknown()).nullable().optional(),
  /** Track A: key identifying the rubric used for qualification */
  qualificationRubricKey: z.string().nullable().optional()
})

export const UpsertCompanyInputSchema = CreateCompanyInputSchema.extend({
  domain: z.string().min(1) // Domain required for upsert (unique key)
})

export const GetCompanyInputSchema = z.object({
  id: z.string().uuid()
})

export const ListCompaniesInputSchema = z.object({
  segment: z.string().optional(),
  category: z.string().optional(),
  domain: z.string().optional().describe('Exact domain match filter'),
  website: z.string().optional().describe('Exact website match filter'),
  processingState: CompanyProcessingStateSchema.optional().describe('JSONB containment filter for processing state'),
  pipelineStatus: z.unknown().optional().describe('@deprecated Use processingState. Compatibility no-op.'),
  batchId: z.string().optional(),
  status: z
    .enum(['active', 'invalid'])
    .optional()
    .describe('Filter by company status. Defaults to active if not set and includeAll is false'),
  includeAll: z
    .boolean()
    .optional()
    .describe('Bypass default active-only filter to return all companies regardless of status'),
  excludeColumns: z
    .array(z.enum(['enrichmentData', 'processingState']))
    .optional()
    .describe('Exclude large JSONB columns from the response to reduce query size')
})

export const DeleteCompanyInputSchema = z.object({
  id: z.string().uuid()
})

export const CompanyOutputSchema = z.object({
  id: z.string().uuid(),
  organizationId: z.string().uuid(),
  name: z.string(),
  domain: z.string().nullable(),
  linkedinUrl: z.string().nullable(),
  website: z.string().nullable(),
  numEmployees: z.number().nullable(),
  foundedYear: z.number().nullable(),
  locationCity: z.string().nullable(),
  locationState: z.string().nullable(),
  category: z.string().nullable(),
  segment: z.string().nullable(),
  processingState: CompanyProcessingStateSchema.nullable(),
  pipelineStatus: z.unknown().nullable().describe('@deprecated Use processingState. Compatibility no-op.'),
  enrichmentData: z.record(z.string(), z.unknown()).nullable(),
  source: z.string().nullable(),
  batchId: z.string().nullable().optional(),
  status: z.enum(['active', 'invalid']),
  createdAt: z.string(),
  updatedAt: z.string()
})

export const CompanyArrayOutputSchema = z.array(CompanyOutputSchema)

// ============================================
// CONTACT SCHEMAS
// ============================================

export const CreateContactInputSchema = z.object({
  email: EmailSchema,
  companyId: z.string().uuid().optional(),
  firstName: z.string().optional(),
  lastName: z.string().optional(),
  linkedinUrl: z.string().url().optional(),
  title: z.string().optional(),
  source: z.string().optional(),
  sourceId: z.string().optional(),
  batchId: z.string().optional(),
  pipelineStatus: z.unknown().optional().describe('@deprecated Use processingState. Compatibility no-op.')
})

export const UpdateContactInputSchema = z.object({
  id: z.string().uuid(),
  companyId: z.string().uuid().optional(),
  emailValid: z.enum(['VALID', 'INVALID', 'RISKY', 'UNKNOWN']).optional(),
  firstName: z.string().optional(),
  lastName: z.string().optional(),
  linkedinUrl: z.string().url().optional(),
  title: z.string().optional(),
  headline: z.string().optional(),
  filterReason: z.string().optional(),
  openingLine: z.string().optional(),
  processingState: ContactProcessingStateSchema.optional(),
  pipelineStatus: z.unknown().optional().describe('@deprecated Use processingState. Compatibility no-op.'),
  enrichmentData: z.record(z.string(), z.unknown()).optional(),
  status: z.enum(['active', 'invalid']).optional()
})

export const UpsertContactInputSchema = CreateContactInputSchema

export const GetContactInputSchema = z.object({
  id: z.string().uuid()
})

export const ListContactsInputSchema = z.object({
  openingLineIsNull: z.boolean().optional(), // Filter to contacts without personalization
  batchId: z.string().optional(),
  contactStatus: z.enum(['active', 'invalid']).optional().describe('Filter by contact status (soft-delete flag)'),
  limit: z.number().int().min(1).max(1000).default(100),
  offset: z.number().int().min(0).default(0)
})

export const DeleteContactInputSchema = z.object({
  id: z.string().uuid()
})

export const DeactivateContactsByCompanyInputSchema = z.object({
  companyId: z.string().uuid()
})

export const DeactivateContactsByCompanyResultSchema = z.object({
  deactivated: z.number()
})

export const BulkImportInputSchema = z.object({
  contacts: z.array(CreateContactInputSchema)
})

export const ContactOutputSchema = z.object({
  id: z.string().uuid(),
  organizationId: z.string().uuid(),
  companyId: z.string().uuid().nullable(),
  email: z.string(),
  emailValid: z.enum(['VALID', 'INVALID', 'RISKY', 'UNKNOWN']).nullable(),
  firstName: z.string().nullable(),
  lastName: z.string().nullable(),
  linkedinUrl: z.string().nullable(),
  title: z.string().nullable(),
  headline: z.string().nullable(),
  filterReason: z.string().nullable(),
  openingLine: z.string().nullable(),
  source: z.string().nullable(),
  sourceId: z.string().nullable(),
  processingState: ContactProcessingStateSchema.nullable(),
  pipelineStatus: z.unknown().nullable().describe('@deprecated Use processingState. Compatibility no-op.'),
  enrichmentData: z.record(z.string(), z.unknown()).nullable(),
  batchId: z.string().nullable().optional(),
  status: z.enum(['active', 'invalid']),
  createdAt: z.string(),
  updatedAt: z.string()
})

export const PaginatedContactsOutputSchema = z.object({
  data: z.array(ContactOutputSchema),
  total: z.number(),
  limit: z.number(),
  offset: z.number()
})

export const BulkImportResultSchema = z.object({
  created: z.number(),
  updated: z.number(),
  errors: z.array(
    z.object({
      email: z.string(),
      error: z.string()
    })
  )
})

export const DeleteResultSchema = z.object({
  success: z.boolean()
})

// ============================================
// INFERRED TYPES
// ============================================

export type CreateListInput = z.infer<typeof CreateListInputSchema>
export type UpdateListInput = z.infer<typeof UpdateListInputSchema>
export type DeleteListInput = z.infer<typeof DeleteListInputSchema>
export type ListOutput = z.infer<typeof ListOutputSchema>

export type CreateCompanyInput = z.infer<typeof CreateCompanyInputSchema>
export type UpdateCompanyInput = z.infer<typeof UpdateCompanyInputSchema>
export type UpsertCompanyInput = z.infer<typeof UpsertCompanyInputSchema>
export type GetCompanyInput = z.infer<typeof GetCompanyInputSchema>
export type ListCompaniesInput = z.infer<typeof ListCompaniesInputSchema>
export type DeleteCompanyInput = z.infer<typeof DeleteCompanyInputSchema>
export type CompanyOutput = z.infer<typeof CompanyOutputSchema>

export type CreateContactInput = z.infer<typeof CreateContactInputSchema>
export type UpdateContactInput = z.infer<typeof UpdateContactInputSchema>
export type UpsertContactInput = z.infer<typeof UpsertContactInputSchema>
export type GetContactInput = z.infer<typeof GetContactInputSchema>
export type ListContactsInput = z.infer<typeof ListContactsInputSchema>
export type DeleteContactInput = z.infer<typeof DeleteContactInputSchema>
export type BulkImportInput = z.infer<typeof BulkImportInputSchema>
export type ContactOutput = z.infer<typeof ContactOutputSchema>
export type PaginatedContactsOutput = z.infer<typeof PaginatedContactsOutputSchema>
export type BulkImportResult = z.infer<typeof BulkImportResultSchema>
export type DeleteResult = z.infer<typeof DeleteResultSchema>
export type DeactivateContactsByCompanyInput = z.infer<typeof DeactivateContactsByCompanyInputSchema>
export type DeactivateContactsByCompanyResult = z.infer<typeof DeactivateContactsByCompanyResultSchema>
