// ─── Tenant (super-admin) ────────────────────────────────────────────────────

export type TenantPlan = 'starter' | 'pro' | 'enterprise'

export interface TenantResponse {
  id: string
  slug: string
  name: string
  plan: TenantPlan
  is_active: boolean
  max_mailboxes: number
  max_users: number
  created_at: string
  updated_at: string
  user_count: number
  mailbox_count: number
}

export interface TenantCreateRequest {
  slug: string
  name: string
  plan?: TenantPlan
  max_mailboxes?: number
  max_users?: number
  admin_email: string
  admin_password: string
  admin_full_name: string
}

export interface TenantUpdateRequest {
  name?: string
  plan?: TenantPlan
  is_active?: boolean
  max_mailboxes?: number
  max_users?: number
}

// ─── Auth ────────────────────────────────────────────────────────────────────

export interface LoginRequest {
  email: string
  password: string
  totp_code?: string
}

export interface TokenResponse {
  access_token: string
  refresh_token: string
  token_type: string
  expires_in: number
}

export interface TOTPSetupResponse {
  secret: string
  qr_uri: string
  qr_image_base64: string
}

export interface TOTPStatusResponse {
  totp_enabled: boolean
}

// ─── User ─────────────────────────────────────────────────────────────────────

export type UserRole = 'super_admin' | 'admin' | 'supervisor' | 'operator' | 'readonly'

export interface UserResponse {
  id: string
  tenant_id: string
  email: string
  full_name: string
  role: UserRole
  is_active: boolean
  totp_enabled: boolean
  last_login_at: string | null
  created_at: string
  updated_at: string
}

export interface UserListResponse {
  items: UserResponse[]
  total: number
  page: number
  page_size: number
  pages: number
}

export interface UserCreateRequest {
  email: string
  password: string
  full_name: string
  role: UserRole
}

export interface UserUpdateRequest {
  full_name?: string
  role?: UserRole
  is_active?: boolean
}

// ─── Mailbox ──────────────────────────────────────────────────────────────────

export type MailboxStatus = 'active' | 'paused' | 'error' | 'deleted'

export interface MailboxResponse {
  id: string
  tenant_id: string
  email_address: string
  display_name: string | null
  provider: string | null
  imap_host: string
  imap_port: number
  imap_use_ssl: boolean
  smtp_host: string
  smtp_port: number
  smtp_use_tls: boolean
  status: MailboxStatus
  last_sync_at: string | null
  last_sync_uid: number | null
  sync_error_msg: string | null
  sync_error_count: number
  created_by: string | null
  created_at: string
  updated_at: string
}

export interface MailboxListResponse {
  items: MailboxResponse[]
  total: number
  page: number
  page_size: number
}

export interface MailboxCreateRequest {
  email_address: string
  display_name?: string
  provider?: string
  imap_host: string
  imap_port: number
  imap_user: string
  imap_pass: string
  imap_use_ssl: boolean
  smtp_host: string
  smtp_port: number
  smtp_user: string
  smtp_pass: string
  smtp_use_tls: boolean
}

export interface MailboxUpdateRequest {
  display_name?: string
  provider?: string
  status?: 'active' | 'paused'
  imap_host?: string
  imap_port?: number
  imap_user?: string
  imap_pass?: string
  imap_use_ssl?: boolean
  smtp_host?: string
  smtp_port?: number
  smtp_user?: string
  smtp_pass?: string
  smtp_use_tls?: boolean
}

export interface ConnectionTestResult {
  success: boolean
  message: string
  latency_ms: number | null
  capabilities: string[] | null
}

// ─── Label (Tag) + Tassonomia (N2) ───────────────────────────────────────────

export interface LabelResponse {
  id: string
  tenant_id: string
  name: string
  color: string | null
  // Tassonomia: se valorizzato, questo nodo fa parte di un albero gerarchico
  parent_id: string | null
  description: string | null
}

/** Nodo tassonomico con figli annidati — restituito da GET /labels/tree */
export interface LabelTreeResponse extends LabelResponse {
  children: LabelTreeResponse[]
}

export interface LabelCreate {
  name: string
  color?: string | null
  parent_id?: string | null
  description?: string | null
}

export interface LabelUpdate {
  name?: string
  color?: string | null
  parent_id?: string | null
  description?: string | null
}

export interface MessageLabelSetRequest {
  label_ids: string[]
}

export interface MessageLabelAddRequest {
  label_ids: string[]
}

export interface MessageLabelRemoveRequest {
  label_ids: string[]
}

export interface MessageBulkLabelRequest {
  message_ids: string[]
  label_ids: string[]
  action: 'add' | 'remove'
}

export interface MessageBulkLabelResponse {
  updated: number
}

// ─── Search match info ────────────────────────────────────────────────────────

export interface AttachmentMatchInfo {
  id: string
  filename: string
}

export interface SearchMatchInfo {
  in_subject: boolean
  in_body: boolean
  in_attachments: AttachmentMatchInfo[]
}

// ─── Rischio e Riservatezza (Feature N3) ─────────────────────────────────────

export type RiskLevel = 'low' | 'medium' | 'high' | 'critical'
export type ConfidentialityLevel = 'public' | 'internal' | 'confidential' | 'secret'

// ─── Message ──────────────────────────────────────────────────────────────────

export type PecDirection = 'inbound' | 'outbound'
export type PecState =
  | 'draft'
  | 'queued'
  | 'sent'
  | 'accepted'
  | 'delivered'
  | 'anomaly'
  | 'failed'
  | 'received'
export type PecMsgType =
  | 'posta_certificata'
  | 'accettazione'
  | 'non_accettazione'
  | 'presa_in_carico'
  | 'avvenuta_consegna'
  | 'mancata_consegna'
  | 'errore_consegna'
  | 'preavviso_mancata_consegna'
  | 'rilevazione_virus'
  | 'unknown'

export interface MessageResponse {
  id: string
  tenant_id: string
  mailbox_id: string
  message_id_header: string | null
  imap_uid: number | null
  imap_folder: string
  direction: PecDirection
  pec_type: PecMsgType
  state: PecState
  subject: string | null
  from_address: string | null
  to_addresses: string[]
  cc_addresses: string[]
  sent_at: string | null
  received_at: string | null
  size_bytes: number | null
  body_text: string | null
  body_html: string | null
  has_attachments: boolean
  parent_message_id: string | null
  is_read: boolean
  is_starred: boolean
  is_archived: boolean
  archived_at: string | null
  is_trashed: boolean
  trashed_at: string | null
  is_pending_conservation: boolean
  pending_conservation_at: string | null
  is_conserved: boolean
  conserved_at: string | null
  // Rischio e Riservatezza (Feature N3)
  risk_level: RiskLevel | null
  confidentiality: ConfidentialityLevel | null
  raw_eml_path: string | null
  created_at: string
  updated_at: string
  labels: LabelResponse[]
  // Popolato solo nelle risposte di ricerca full-text
  search_match?: SearchMatchInfo | null
}

export interface MessageListResponse {
  items: MessageResponse[]
  total: number
  page: number
  page_size: number
}

// ─── Attachment ───────────────────────────────────────────────────────────────

export interface AttachmentResponse {
  id: string
  message_id: string
  filename: string
  content_type: string | null
  size_bytes: number | null
  storage_path: string
  checksum_sha256: string | null
  created_at: string
}

// ─── Send Job ─────────────────────────────────────────────────────────────────

export type SendJobStatus = 'pending' | 'sending' | 'sent' | 'failed' | 'retrying'

export interface SendJobResponse {
  id: string
  tenant_id: string
  mailbox_id: string
  message_id: string | null
  status: SendJobStatus
  attempt_count: number
  max_attempts: number
  next_retry_at: string | null
  last_error: string | null
  queued_at: string
  sent_at: string | null
  created_by: string | null
}

export interface SendJobListResponse {
  items: SendJobResponse[]
  total: number
  page: number
  page_size: number
}

export interface SendPecRequest {
  mailbox_id: string
  to_addresses: string[]
  cc_addresses?: string[]
  subject: string
  body_text?: string
  body_html?: string
  reply_to_message_id?: string
}

// ─── Permission ───────────────────────────────────────────────────────────────

export interface PermissionResponse {
  id: string
  tenant_id: string
  user_id: string
  mailbox_id: string
  can_read: boolean
  can_send: boolean
  can_manage: boolean
  can_conserve: boolean
  granted_by: string | null
  granted_at: string
}

export interface PermissionGrantRequest {
  can_read?: boolean
  can_send?: boolean
  can_manage?: boolean
  can_conserve?: boolean
}

export interface MailboxUserPermissionResponse {
  user_id: string
  user_email: string
  user_full_name: string
  user_role: UserRole
  can_read: boolean
  can_send: boolean
  can_manage: boolean
  can_conserve: boolean
  granted_at: string
}

// ─── Permission Preset (sottoruoli) ───────────────────────────────────────────

export interface PermissionPresetResponse {
  id: string
  tenant_id: string
  name: string
  description: string | null
  can_read: boolean
  can_send: boolean
  can_manage: boolean
  can_conserve: boolean
  created_by: string | null
  created_at: string
  updated_at: string
}

export interface PermissionPresetCreate {
  name: string
  description?: string | null
  can_read?: boolean
  can_send?: boolean
  can_manage?: boolean
  can_conserve?: boolean
}

export interface PermissionPresetUpdate {
  name?: string
  description?: string | null
  can_read?: boolean
  can_send?: boolean
  can_manage?: boolean
  can_conserve?: boolean
}

export interface UserMailboxPermissionResponse {
  mailbox_id: string
  email_address: string
  display_name: string | null
  can_read: boolean
  can_send: boolean
  can_manage: boolean
  can_conserve: boolean
}

// ─── Virtual Box ──────────────────────────────────────────────────────────────

export type VBoxField = 'mailbox_id' | 'imap_folder' | 'subject' | 'from_address' | 'to_address'
export type VBoxOperator = 'contains' | 'equals' | 'starts_with' | 'ends_with' | 'regex'

export interface VirtualBoxRuleCreate {
  field: VBoxField
  operator: VBoxOperator
  value: string
  date_from?: string | null
  date_to?: string | null
}

export interface VirtualBoxRuleResponse {
  id: string
  virtual_box_id: string
  field: string
  operator: string
  value: string
  date_from: string | null
  date_to: string | null
  created_at: string
}

export interface MailboxBriefResponse {
  id: string
  email_address: string
  display_name: string | null
  status: string
}

export interface VirtualBoxCreate {
  name: string
  description?: string | null
  label?: string | null
  rules?: VirtualBoxRuleCreate[]
  mailbox_ids?: string[]
}

export interface VirtualBoxUpdate {
  name?: string
  description?: string | null
  label?: string | null
  is_active?: boolean
  mailbox_ids?: string[] | null
}

export interface VirtualBoxMailboxAssignRequest {
  mailbox_ids: string[]
}

export interface VirtualBoxResponse {
  id: string
  tenant_id: string
  name: string
  description: string | null
  label: string | null
  is_active: boolean
  created_by: string | null
  created_at: string
  updated_at: string
  rules: VirtualBoxRuleResponse[]
  assignment_count: number
  mailboxes: MailboxBriefResponse[]
}

export interface VirtualBoxListResponse {
  items: VirtualBoxResponse[]
  total: number
  page: number
  page_size: number
}

export interface VirtualBoxAssignRequest {
  user_ids: string[]
}

export interface VirtualBoxAssignmentResponse {
  id: string
  virtual_box_id: string
  user_id: string
  assigned_by: string | null
  assigned_at: string
}

export interface AssignedUserResponse {
  user_id: string
  user_email: string
  user_full_name: string
  assigned_at: string
}

// ─── Notifications ────────────────────────────────────────────────────────────

export type NotificationChannelType = 'webhook' | 'email' | 'telegram' | 'whatsapp'
export type NotificationEventType =
  | 'new_message'
  | 'state_changed'
  | 'anomaly'
  | 'send_failed'
  | 'send_delivered'
  | 'mailbox_error'
export type NotificationStatus = 'pending' | 'sent' | 'failed' | 'skipped'

export interface NotificationChannelCreate {
  name: string
  channel_type: NotificationChannelType
  config?: Record<string, unknown> | null
  config_secret?: Record<string, unknown> | null
}

export interface NotificationChannelUpdate {
  name?: string
  is_active?: boolean
  config?: Record<string, unknown> | null
  config_secret?: Record<string, unknown> | null
}

export interface NotificationChannelResponse {
  id: string
  tenant_id: string
  name: string
  channel_type: NotificationChannelType
  is_active: boolean
  config: Record<string, unknown> | null
  consecutive_failures: number
  circuit_open_until: string | null
  created_by: string | null
  created_at: string
  updated_at: string
}

export interface NotificationChannelListResponse {
  items: NotificationChannelResponse[]
  total: number
  page: number
  page_size: number
}

export interface ChannelTestResult {
  success: boolean
  message: string
  http_status: number | null
}

export interface NotificationRuleCreate {
  channel_id: string
  name: string
  event_type: NotificationEventType
  filter?: Record<string, unknown> | null
}

export interface NotificationRuleUpdate {
  name?: string
  event_type?: NotificationEventType
  filter?: Record<string, unknown> | null
  is_active?: boolean
}

export interface NotificationRuleResponse {
  id: string
  tenant_id: string
  channel_id: string
  name: string
  event_type: string
  filter: Record<string, unknown> | null
  is_active: boolean
  created_at: string
}

export interface NotificationRuleListResponse {
  items: NotificationRuleResponse[]
  total: number
}

export interface NotificationLogResponse {
  id: string
  tenant_id: string
  channel_id: string
  rule_id: string | null
  event_type: string
  status: NotificationStatus
  attempt_count: number
  max_attempts: number
  next_retry_at: string | null
  last_error: string | null
  http_status: number | null
  sent_at: string | null
  created_at: string
}

export interface NotificationLogListResponse {
  items: NotificationLogResponse[]
  total: number
  page: number
  page_size: number
}

// ─── WebSocket events ─────────────────────────────────────────────────────────

export type WsEventType =
  | 'mailbox:new_message'
  | 'mailbox:status_changed'
  | 'send_job:status_changed'
  | 'send_job:anomaly'

export interface WsEvent {
  type: WsEventType
  tenant_id: string
  payload: Record<string, unknown>
}

// ─── API Pagination ──────────────────────────────────────────────────────────

export interface PaginatedResponse<T> {
  items: T[]
  total: number
  page: number
  page_size: number
  pages: number
}

export interface PaginationParams {
  page?: number
  page_size?: number
}

export interface ApiError {
  detail: string | Array<{ loc: string[]; msg: string; type: string }>
}
