export const SOURCE_TYPES = ['gmail', 'monday_api', 'monday_chrome', 'demo'] as const;
export type SourceType = (typeof SOURCE_TYPES)[number];

export const DECISIONS = ['pending', 'approved', 'ignored', 'auto_ignored'] as const;
export type Decision = (typeof DECISIONS)[number];

export const STATUSES = [
  'none',
  'approved',
  'claimed',
  'created',
  'in_progress',
  'completed',
  'failed',
] as const;
export type Status = (typeof STATUSES)[number];

export interface AttachmentMeta {
  filename: string;
  mimeType?: string;
  size?: number;
  sourceRef?: string;
  url?: string;
}

export interface IntakeItem {
  id: string;
  source_type: SourceType;
  source_account: string | null;
  source_external_id: string;
  source_url: string | null;
  sender_id: string | null;
  sender_name: string | null;
  sender_email: string | null;
  client_project: string | null;
  title: string;
  body: string;
  metadata: Record<string, unknown>;
  attachments: AttachmentMeta[];
  parse_warnings: string[];
  raw_payload: unknown;
  received_at: string;
  ingested_at: string;
  decision: Decision;
  status: Status;
  maj_wp_ticket_id: string | null;
  remote_status: string | null;
  remote_message: string | null;
  last_sync_at: string | null;
  error: string | null;
  claim_token: string | null;
  claim_expires_at: string | null;
  claimed_by: string | null;
  idempotency_key: string;
}

export interface IgnoredSender {
  id: string;
  sender_type: 'email' | 'monday_user';
  sender_key: string;
  sender_label: string | null;
  reason: string | null;
  created_at: string;
  active: boolean;
}

export interface IngestInput {
  source_type: SourceType;
  source_account?: string | null;
  source_external_id: string;
  source_url?: string | null;
  sender_id?: string | null;
  sender_name?: string | null;
  sender_email?: string | null;
  client_project?: string | null;
  title: string;
  body?: string;
  metadata?: Record<string, unknown>;
  attachments?: AttachmentMeta[];
  parse_warnings?: string[];
  raw_payload?: unknown;
  received_at?: string;
}

export interface IntakeListFilters {
  decision?: Decision | Decision[];
  status?: Status | Status[];
  source_type?: SourceType;
  limit?: number;
  offset?: number;
}

export function isTerminalStatus(status: Status): boolean {
  return status === 'completed' || status === 'failed';
}

export function canClaim(item: Pick<IntakeItem, 'decision' | 'status' | 'claim_expires_at'>): boolean {
  if (item.decision !== 'approved') return false;
  if (item.status === 'claimed') {
    if (!item.claim_expires_at) return false;
    return new Date(item.claim_expires_at) < new Date();
  }
  return item.status === 'none' || item.status === 'approved';
}
