import {
  OrderStatus,
  SubscriptionTier,
  SubscriptionPlan,
  SubscriptionStatus,
  UserStatus,
  LogLevel,
  JobStatus,
  AutomationMode,
} from '@prisma/client'

// Re-export enums for use as both types and values
export {
  OrderStatus,
  SubscriptionTier,
  SubscriptionPlan,
  SubscriptionStatus,
  UserStatus,
  LogLevel,
  JobStatus,
  AutomationMode,
}

// User types
export interface UserSummary {
  id: string
  name: string | null
  email: string
  company: string | null
}

export interface User extends UserSummary {
  status: UserStatus
  emailVerified: Date | null
  createdAt: Date
  updatedAt: Date
}

// Subscription types
export interface Subscription {
  id: string
  userId: string
  plan: SubscriptionPlan
  tier: SubscriptionTier
  tokenLimit: number
  tokensUsed: number
  trialEndsAt: Date | null
  stripeCustomerId: string | null
  stripeSubscriptionId: string | null
  status: SubscriptionStatus
  createdAt: Date
  updatedAt: Date
}

// Provisioning log types
export interface ProvisioningLog {
  id: string
  orderId: string
  level: LogLevel
  message: string
  step: string | null
  timestamp: Date
}

// Job types
export interface JobSummary {
  id: string
  status: JobStatus
  attempt: number
  maxAttempts: number
  createdAt: Date
  completedAt: Date | null
  error: string | null
}

// Order types
export interface Order {
  id: string
  userId: string
  status: OrderStatus
  tier: SubscriptionTier
  domain: string
  tools: string[]
  configJson: Record<string, unknown>
  serverIp: string | null
  sshPort: number
  portainerUrl: string | null
  dashboardUrl: string | null
  failureReason: string | null
  createdAt: Date
  updatedAt: Date
  serverReadyAt: Date | null
  provisioningStartedAt: Date | null
  completedAt: Date | null
  // Provisioning config fields
  customer: string | null
  companyName: string | null
  licenseKey: string | null
  hubApiKey: string | null
  // Automation fields
  automationMode: AutomationMode
  automationPausedAt: Date | null
  automationPausedReason: string | null
  source: string | null
  // Netcup integration
  netcupServerId: string | null
  user: UserSummary
  _count?: {
    provisioningLogs: number
  }
}

export interface OrderDetail extends Omit<Order, '_count'> {
  provisioningLogs: ProvisioningLog[]
  jobs: JobSummary[]
}

// Customer types (User with subscriptions and orders)
export interface Customer extends User {
  subscriptions: Subscription[]
  orders: Order[]
  _count: {
    orders: number
    subscriptions: number
    tokenUsage?: number
  }
  // Computed fields from API
  totalTokensUsed?: number
  tokenLimit?: number
}

export interface CustomerSummary extends UserSummary {
  status: UserStatus
  createdAt: Date
  _count: {
    orders: number
    subscriptions: number
  }
  subscriptions: {
    id: string
    plan: SubscriptionPlan
    tier: SubscriptionTier
    status: SubscriptionStatus
  }[]
}

// API response types
export interface PaginatedResponse<T> {
  pagination: {
    page: number
    limit: number
    total: number
    totalPages: number
  }
}

export interface OrdersResponse extends PaginatedResponse<Order> {
  orders: Order[]
}

export interface CustomersResponse extends PaginatedResponse<CustomerSummary> {
  customers: CustomerSummary[]
}

// Dashboard stats types
export interface DashboardStats {
  orders: {
    total: number
    pending: number
    inProgress: number
    completed: number
    failed: number
    byStatus: Record<OrderStatus, number>
  }
  customers: {
    total: number
    active: number
    suspended: number
    pending: number
  }
  subscriptions: {
    total: number
    trial: number
    active: number
    byPlan: Record<SubscriptionPlan, number>
    byTier: Record<SubscriptionTier, number>
  }
  recentOrders: Order[]
}

// API filter types
export interface OrderFilters {
  status?: OrderStatus
  tier?: SubscriptionTier
  search?: string
  page?: number
  limit?: number
}

export interface CustomerFilters {
  status?: UserStatus
  search?: string
  page?: number
  limit?: number
}

// Mutation types
export interface UpdateOrderPayload {
  status?: OrderStatus
  serverIp?: string
  serverPassword?: string
  sshPort?: number
  failureReason?: string
  tools?: string[]
  domain?: string
  // Provisioning config fields
  customer?: string
  companyName?: string
  licenseKey?: string
  // Netcup linking
  netcupServerId?: string | null
}

export interface CreateOrderPayload {
  userId: string
  domain: string
  tier: SubscriptionTier
  tools: string[]
}

export interface ProvisioningResult {
  success: boolean
  message: string
  jobId?: string
}

export interface CreateCustomerPayload {
  email: string
  name?: string
  company?: string
  status?: UserStatus
}

// Settings types
export interface SystemSetting {
  key: string
  value: string
  encrypted: boolean
  category: string
  maskedValue?: string
  updatedAt: Date
}

export interface SettingsResponse {
  settings: SystemSetting[]
  grouped: Record<string, SystemSetting[]>
  categories: string[]
}

export interface UpdateSettingsPayload {
  settings: Array<{ key: string; value: string }>
}

export interface UpdateSettingPayload {
  value: string
}

// Enterprise Client types
export type ErrorSeverity = 'INFO' | 'WARNING' | 'ERROR' | 'CRITICAL'

export interface EnterpriseClient {
  id: string
  name: string
  companyName: string | null
  contactEmail: string
  contactPhone: string | null
  notes: string | null
  isActive: boolean
  createdAt: Date
  updatedAt: Date
}

export interface EnterpriseServer {
  id: string
  clientId: string
  netcupServerId: string
  nickname: string | null
  purpose: string | null
  isActive: boolean
  createdAt: Date
  updatedAt: Date
  portainerUrl: string | null
  portainerUsername: string | null
}

export interface EnterpriseServerWithStatus extends EnterpriseServer {
  netcupStatus: string
  netcupHostname: string | null
  netcupIps: string[]
}

export interface ClientStatsOverview {
  totalServers: number
  activeServers: number
  totalContainers: number
  runningContainers: number
  stoppedContainers: number
  unacknowledgedErrors: number
  avgCpuPercent: number | null
  avgMemoryPercent: number | null
}

export interface EnterpriseClientWithDetails extends EnterpriseClient {
  servers: EnterpriseServer[]
  _count: {
    servers: number
    errorRules: number
  }
  statsOverview?: ClientStatsOverview
}

export interface ErrorDetectionRule {
  id: string
  clientId: string
  name: string
  pattern: string
  severity: ErrorSeverity
  isActive: boolean
  description: string | null
  createdAt: Date
  updatedAt: Date
  _count?: {
    detectedErrors: number
  }
}

export interface DetectedError {
  id: string
  serverId: string
  ruleId: string
  containerId: string | null
  containerName: string | null
  logLine: string
  context: string | null
  timestamp: Date
  acknowledgedAt: Date | null
  acknowledgedBy: string | null
  server?: {
    id: string
    nickname: string | null
    netcupServerId: string
  }
  rule?: {
    id: string
    name: string
    severity: ErrorSeverity
  }
}

// Enterprise Client API payload types
export interface CreateEnterpriseClientPayload {
  name: string
  companyName?: string
  contactEmail: string
  contactPhone?: string
  notes?: string
}

export interface UpdateEnterpriseClientPayload {
  name?: string
  companyName?: string | null
  contactEmail?: string
  contactPhone?: string | null
  notes?: string | null
  isActive?: boolean
}

export interface AddServerPayload {
  netcupServerId: string
  nickname?: string
  purpose?: string
  portainerUrl?: string
  portainerUsername?: string
  portainerPassword?: string
}

export interface UpdateServerPayload {
  nickname?: string | null
  purpose?: string | null
  isActive?: boolean
  portainerUrl?: string | null
  portainerUsername?: string | null
  portainerPassword?: string
}

export type ServerActionPayload = {
  action: 'power'
  command: 'ON' | 'OFF' | 'POWERCYCLE' | 'RESET' | 'POWEROFF'
} | {
  action: 'wipe' | 'reinstall'
  verificationCode: string
  imageId?: string
}

export interface CreateErrorRulePayload {
  name: string
  pattern: string
  severity?: ErrorSeverity
  description?: string
}

export interface UpdateErrorRulePayload {
  name?: string
  pattern?: string
  severity?: ErrorSeverity
  description?: string | null
  isActive?: boolean
}

export interface ErrorFilters {
  serverId?: string
  severity?: ErrorSeverity
  acknowledged?: boolean
  limit?: number
}
