import type { ApiLLMSettings, ApiSearchSettings } from "@/lib/contacts/discovery-types"

export type ApiOrgAuthentik = {
  enabled: boolean
  api_url: string
  slug: string
  client_id: string
  enforce_sso: boolean
  allow_password_fallback: boolean
  default_groups: string
}

export type ApiIdentityProviderOAuth = {
  provider: "google" | "github" | "linkedin" | "microsoft" | "custom"
  client_id: string
  client_secret: string
  scopes: string
  authorization_url?: string
  token_url?: string
  profile_url?: string
}

export type ApiIdentityProviderSAML = {
  metadata_url?: string
  metadata_xml?: string
  entity_id?: string
  sso_url?: string
  slo_url?: string
  signing_cert?: string
}

export type ApiIdentityProviderLDAP = {
  server_uri: string
  bind_dn: string
  bind_password: string
  base_dn: string
  user_filter?: string
  start_tls: boolean
  sync_users?: boolean
}

export type ApiIdentityProvider = {
  id: string
  name: string
  slug: string
  type: "oauth" | "saml" | "ldap"
  enabled: boolean
  authentik_pk?: number
  sync_status: "pending" | "synced" | "error"
  sync_error?: string
  last_synced_at?: string
  allowed_email_domains: string[]
  allowed_identities: string[]
  allowed_organizations: string[]
  default_groups: string[]
  oauth?: ApiIdentityProviderOAuth
  saml?: ApiIdentityProviderSAML
  ldap?: ApiIdentityProviderLDAP
}

export type ApiIdentityProvidersPolicy = {
  allow_self_enrollment: boolean
  default_login_source?: string
  providers: ApiIdentityProvider[]
}

export type ApiOrgTwoFactor = {
  required_for_all: boolean
  required_for_admins: boolean
  allowed_methods: ("totp" | "webauthn")[]
  grace_period_days: number
  remember_device_days: number
}

export type ApiOrgStorageQuotas = {
  default_mail_gib: number
  default_drive_gib: number
  default_photos_gib: number
  warn_threshold_pct: number
}

export type ApiOrgUsageQuotas = {
  llm_daily_cost_limit_eur: number
  llm_monthly_cost_limit_eur: number
  llm_cost_warn_threshold_pct: number
  llm_requests_per_day: number
  llm_tokens_per_month: number
  search_requests_per_day: number
  max_api_tokens_per_user: number
  max_webhooks_per_user: number
}

export type ApiOrgFilePolicies = {
  max_upload_mib: number
  allowed_extensions: string
  block_executable: boolean
  external_sharing: "disabled" | "authenticated" | "public_link"
  default_link_expiry_days: number
  virus_scan_enabled: boolean
  virustotal_api_key: string
  retention_trash_days: number
  mount_oauth?: {
    redirect_uri?: string
    google?: { enabled?: boolean; client_id?: string; client_secret?: string }
    dropbox?: { enabled?: boolean; client_id?: string; client_secret?: string }
    microsoft?: { enabled?: boolean; client_id?: string; client_secret?: string }
  }
}

export type ApiOrgLLMSettings = ApiLLMSettings & {
  enforce_org_providers: boolean
  allow_user_override: boolean
}

export type ApiOrgSearchSettings = {
  suite_engine: "postgres" | "meilisearch" | "typesense"
  meilisearch_url: string
  meilisearch_api_key: string
  typesense_url: string
  typesense_api_key: string
  web_search: ApiSearchSettings
  enforce_org_search: boolean
}

export type ApiOrgAdministrator = {
  id: string
  email: string
  name: string
  external_id?: string
  scopes: ("read" | "write")[]
  added_at: string
}

export type ApiOrgNextcloud = {
  enabled: boolean
  base_url: string
  admin_user: string
  admin_password: string
  drive_enabled: boolean
  calendar_enabled: boolean
  contacts_enabled: boolean
  talk_enabled: boolean
}

export type ApiOrgMailing = {
  enabled: boolean
  smtp_host: string
  smtp_port: number
  smtp_user: string
  smtp_password: string
  from_email: string
  from_name: string
  tls_mode: "starttls" | "ssl" | "none"
  reply_to?: string
}

export type ApiOrgOnlyoffice = {
  enabled: boolean
  document_server_url: string
  jwt_secret: string
  jwt_header: string
}

export type ApiOrgRichText = {
  enabled: boolean
  storage_mode: "sidecar" | "overwrite"
  export_mirror_format: "" | "docx"
  hocuspocus_url: string
}

export type ApiOrgAiAssistant = {
  enabled: boolean
  openwebui_internal_url: string
  public_path: string
  embed_default_temporary: boolean
  default_model: string
  enabled_tools: string[]
  chat_sync_enabled: boolean
  chat_nc_path: string
  models?: ApiOrgAiModelCatalogEntry[]
}

export type ApiOrgAiModelCatalogEntry = {
  model_id: string
  label: string
  enabled: boolean
}

export type ApiOrgAgenda = {
  default_theme_mode: "light" | "dark" | "system"
  enforce_org_theme: boolean
  default_video_provider: "ultimeet" | "google_meet" | "zoom" | "teams" | "jitsi" | "none"
  enforce_org_video_provider: boolean
  video_provider_api_keys: Record<string, string>
}

export type ApiOrgMeetPostActions = {
  email_enabled: boolean
  email_recipients: "organizer" | "participants" | "both" | "custom"
  email_custom_addresses: string
  drive_enabled: boolean
  drive_folder_path: string
  llm_enabled: boolean
  llm_provider_id: string
  llm_prompt: string
  llm_then_email: boolean
  llm_then_drive: boolean
}

export type ApiOrgMeet = {
  transcription_enabled: boolean
  transcription_mode: "live" | "queued"
  transcription_engine: "faster_whisper_local" | "external_api"
  skynet_url: string
  whisper_model: string
  external_api_url: string
  external_api_provider: "openai_compatible" | "deepgram" | "google" | "custom"
  external_api_key: string
  auto_start_transcription: boolean
  post_actions: ApiOrgMeetPostActions
}

export type ApiOrgPlugin = {
  id: string
  name: string
  description: string
  enabled: boolean
  version: string
}

export type ApiOrgIntegration = {
  id: string
  name: string
  description: string
  enabled: boolean
  configured: boolean
}

export type ApiOrgPolicy = {
  authentik: ApiOrgAuthentik
  identity_providers: ApiIdentityProvidersPolicy
  two_factor: ApiOrgTwoFactor
  storage_quotas: ApiOrgStorageQuotas
  usage_quotas: ApiOrgUsageQuotas
  file_policies: ApiOrgFilePolicies
  llm: ApiOrgLLMSettings
  search: ApiOrgSearchSettings
  administrators: ApiOrgAdministrator[]
  nextcloud: ApiOrgNextcloud
  mailing: ApiOrgMailing
  onlyoffice: ApiOrgOnlyoffice
  richtext?: ApiOrgRichText
  ai_assistant?: ApiOrgAiAssistant
  agenda?: ApiOrgAgenda
  meet?: ApiOrgMeet
  plugins: ApiOrgPlugin[]
  integrations: ApiOrgIntegration[]
}

export type ApiOrgEffective = {
  authentik: {
    enabled: boolean
    api_url: string
    client_id: string
    issuer?: string
  }
  nextcloud: {
    enabled: boolean
    base_url: string
    admin_user: string
  }
  onlyoffice: {
    enabled: boolean
    document_server_url: string
  }
  search: {
    suite_engine: string
    meilisearch_url: string
    typesense_url: string
  }
  immich?: {
    enabled: boolean
    api_url: string
  }
  jitsi?: {
    enabled: boolean
    public_url: string
  }
  ai_assistant?: {
    enabled: boolean
    openwebui_internal_url: string
    public_path: string
  }
  identity_providers?: {
    authentik_public_url: string
    oauth_redirect_template: string
  }
}

export type ApiOrgEnvVar = {
  name: string
  group: string
  set: boolean
  secret: boolean
  value?: string
}

export type ApiOrgDeployLock = {
  locked: boolean
  reason: string
  fields: string[]
}

export type ApiOrgDeployLocked = Record<string, ApiOrgDeployLock>

export type ApiOrgSettingsResponse = {
  policy: ApiOrgPolicy
  effective: ApiOrgEffective
  secrets: Record<string, { configured: boolean } | Record<string, Record<string, { configured?: boolean }>>>
  env_vars: ApiOrgEnvVar[]
  deploy_locked: ApiOrgDeployLocked
  updated_at: string
  updated_by: string
}

export type ApiOrgSettingsPutRequest = {
  policy: Partial<ApiOrgPolicy>
}

export type OrgPolicySectionKey = keyof ApiOrgPolicy
