import { ULTICAL_APP_NAME } from "@/lib/suite/page-metadata"

export type ApiTokenPermissionGroup = "mail" | "drive" | "contacts" | "agenda" | "automation"

export type ApiTokenAccess = "read" | "write"

export interface ApiTokenPermissionDef {
  id: string
  label: string
  description: string
  group: ApiTokenPermissionGroup
  supportsRead: boolean
  supportsWrite: boolean
}

export interface ApiTokenPermissionGrant {
  resource: string
  read: boolean
  write: boolean
}

export interface ApiTokenMailScope {
  all_accounts: boolean
  account_ids: string[]
}

export interface ApiTokenDriveScope {
  all_folders: boolean
  folder_paths: string[]
}

export interface ApiTokenAgendaScope {
  all_calendars: boolean
  calendar_ids: string[]
}

export const API_TOKEN_PERMISSION_GROUPS: {
  id: ApiTokenPermissionGroup
  label: string
  description: string
}[] = [
  {
    id: "mail",
    label: "Mail",
    description: "Boîtes, messages, libellés, identités et pièces jointes.",
  },
  {
    id: "drive",
    label: "Drive",
    description: "Fichiers, dossiers, partage et téléchargement.",
  },
  {
    id: "contacts",
    label: "Contacts",
    description: "Annuaire, libellés et propriétés des contacts.",
  },
  {
    id: "agenda",
    label: ULTICAL_APP_NAME,
    description: "Calendriers, événements, disponibilités et réponses aux invitations.",
  },
  {
    id: "automation",
    label: "Automatisations",
    description: "Règles, webhooks, fournisseurs et administration des tokens.",
  },
]

export const API_TOKEN_PERMISSIONS: ApiTokenPermissionDef[] = [
  {
    id: "mail.mailboxes",
    label: "Boîtes et dossiers",
    description: "Lister et organiser les dossiers IMAP/unifiés.",
    group: "mail",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "mail.labels",
    label: "Libellés",
    description: "Consulter et gérer les libellés unifiés.",
    group: "mail",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "mail.messages",
    label: "Messages",
    description: "Lire le contenu des messages autorisés.",
    group: "mail",
    supportsRead: true,
    supportsWrite: false,
  },
  {
    id: "mail.search",
    label: "Recherche",
    description: "Rechercher dans les messages des comptes autorisés.",
    group: "mail",
    supportsRead: true,
    supportsWrite: false,
  },
  {
    id: "mail.send",
    label: "Envoi",
    description: "Envoyer des messages via les identités autorisées.",
    group: "mail",
    supportsRead: false,
    supportsWrite: true,
  },
  {
    id: "mail.attachments",
    label: "Pièces jointes",
    description: "Télécharger et joindre des fichiers aux messages.",
    group: "mail",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "mail.settings",
    label: "Configuration",
    description: "Préférences mail, signatures et organisation.",
    group: "mail",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "mail.identities",
    label: "Identités",
    description: "Identités d'envoi et alias configurés.",
    group: "mail",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "mail.automation",
    label: "Automatisations mail",
    description: "Règles et actions liées aux messages.",
    group: "mail",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "drive.folders",
    label: "Dossiers",
    description: "Parcourir l'arborescence Drive.",
    group: "drive",
    supportsRead: true,
    supportsWrite: false,
  },
  {
    id: "drive.files",
    label: "Fichiers",
    description: "Lire le contenu et les métadonnées des fichiers.",
    group: "drive",
    supportsRead: true,
    supportsWrite: false,
  },
  {
    id: "drive.thumbnails",
    label: "Miniatures",
    description: "Obtenir les vignettes de prévisualisation.",
    group: "drive",
    supportsRead: true,
    supportsWrite: false,
  },
  {
    id: "drive.download",
    label: "Liens de téléchargement",
    description: "Générer des liens de téléchargement temporaires.",
    group: "drive",
    supportsRead: true,
    supportsWrite: false,
  },
  {
    id: "drive.share",
    label: "Liens de partage",
    description: "Créer et gérer les partages publics.",
    group: "drive",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "drive.upload",
    label: "Upload",
    description: "Envoyer des fichiers et dossiers.",
    group: "drive",
    supportsRead: false,
    supportsWrite: true,
  },
  {
    id: "drive.rename",
    label: "Renommage",
    description: "Renommer fichiers et dossiers.",
    group: "drive",
    supportsRead: false,
    supportsWrite: true,
  },
  {
    id: "drive.move",
    label: "Déplacement",
    description: "Déplacer fichiers et dossiers.",
    group: "drive",
    supportsRead: false,
    supportsWrite: true,
  },
  {
    id: "drive.copy",
    label: "Copie",
    description: "Dupliquer fichiers et dossiers.",
    group: "drive",
    supportsRead: false,
    supportsWrite: true,
  },
  {
    id: "contacts.read",
    label: "Lecture",
    description: "Consulter les fiches contacts.",
    group: "contacts",
    supportsRead: true,
    supportsWrite: false,
  },
  {
    id: "contacts.search",
    label: "Recherche",
    description: "Rechercher dans l'annuaire.",
    group: "contacts",
    supportsRead: true,
    supportsWrite: false,
  },
  {
    id: "contacts.write",
    label: "Création et modification",
    description: "Ajouter et modifier des contacts et leurs propriétés.",
    group: "contacts",
    supportsRead: false,
    supportsWrite: true,
  },
  {
    id: "contacts.delete",
    label: "Suppression",
    description: "Supprimer des contacts.",
    group: "contacts",
    supportsRead: false,
    supportsWrite: true,
  },
  {
    id: "contacts.labels",
    label: "Libellés de contacts",
    description: "Gérer les groupes et libellés de contacts.",
    group: "contacts",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "agenda.calendars",
    label: "Calendriers",
    description: "Lister et gérer les agendas.",
    group: "agenda",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "agenda.events",
    label: "Événements",
    description: "Consulter les événements des agendas autorisés.",
    group: "agenda",
    supportsRead: true,
    supportsWrite: false,
  },
  {
    id: "agenda.events.write",
    label: "Création et modification",
    description: "Créer et modifier des événements.",
    group: "agenda",
    supportsRead: false,
    supportsWrite: true,
  },
  {
    id: "agenda.events.delete",
    label: "Suppression",
    description: "Supprimer des événements.",
    group: "agenda",
    supportsRead: false,
    supportsWrite: true,
  },
  {
    id: "agenda.freebusy",
    label: "Disponibilités",
    description: "Interroger les créneaux libres/occupés.",
    group: "agenda",
    supportsRead: true,
    supportsWrite: false,
  },
  {
    id: "agenda.response",
    label: "Réponses aux invitations",
    description: "Accepter, refuser ou marquer provisoire une invitation.",
    group: "agenda",
    supportsRead: false,
    supportsWrite: true,
  },
  {
    id: "automation.rules",
    label: "Règles",
    description: "Règles de tri et workflows.",
    group: "automation",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "automation.webhooks",
    label: "Webhooks",
    description: "Webhooks sortants et templates.",
    group: "automation",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "automation.llm",
    label: "Fournisseurs LLM",
    description: "Configuration des fournisseurs IA.",
    group: "automation",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "automation.chat",
    label: "Chat UltiAI",
    description: "Sessions assistant IA, completions et sync historique.",
    group: "automation",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "automation.search",
    label: "Fournisseurs de recherche",
    description: "Moteurs de recherche externes.",
    group: "automation",
    supportsRead: true,
    supportsWrite: true,
  },
  {
    id: "automation.api_tokens",
    label: "Super admin — Tokens API",
    description: "Créer, modifier et révoquer d'autres tokens API.",
    group: "automation",
    supportsRead: false,
    supportsWrite: true,
  },
]

export function emptyPermissionGrants(): ApiTokenPermissionGrant[] {
  return API_TOKEN_PERMISSIONS.map((def) => ({
    resource: def.id,
    read: false,
    write: false,
  }))
}

export function defaultMailScope(): ApiTokenMailScope {
  return { all_accounts: true, account_ids: [] }
}

export function defaultDriveScope(): ApiTokenDriveScope {
  return { all_folders: true, folder_paths: [] }
}

export function defaultAgendaScope(): ApiTokenAgendaScope {
  return { all_calendars: true, calendar_ids: [] }
}

export function hasAnyPermission(grants: ApiTokenPermissionGrant[]): boolean {
  return grants.some((g) => g.read || g.write)
}

export function hasMailPermissions(grants: ApiTokenPermissionGrant[]): boolean {
  return grants.some(
    (g) =>
      g.resource.startsWith("mail.") &&
      (g.read || g.write)
  )
}

export function hasDrivePermissions(grants: ApiTokenPermissionGrant[]): boolean {
  return grants.some(
    (g) =>
      g.resource.startsWith("drive.") &&
      (g.read || g.write)
  )
}

export function hasAgendaPermissions(grants: ApiTokenPermissionGrant[]): boolean {
  return grants.some(
    (g) =>
      g.resource.startsWith("agenda.") &&
      (g.read || g.write)
  )
}

export function summarizePermissions(grants: ApiTokenPermissionGrant[]): string[] {
  const lines: string[] = []
  for (const def of API_TOKEN_PERMISSIONS) {
    const grant = grants.find((g) => g.resource === def.id)
    if (!grant) continue
    const parts: string[] = []
    if (grant.read && def.supportsRead) parts.push("lecture")
    if (grant.write && def.supportsWrite) parts.push("écriture")
    if (parts.length > 0) lines.push(`${def.label} (${parts.join(", ")})`)
  }
  return lines
}
