import type { AuditEvent } from "../../entities/audit/types";
import type { AccessRequest } from "../../entities/access-request/types";
import type { EngineWorkflowAccessRequest } from "../../entities/engine-workflow-access-request/types";
import type { TaskerInviteRequest } from "../../entities/tasker-invite-request/types";
import type { Client } from "../../entities/client/types";
import type { Invite } from "../../entities/invite/types";
import type { Service } from "../../entities/service/types";
import type { SyncStatus } from "../../entities/sync/types";
import type { ClientGroup, ClientMembership, LauncherUser } from "../../entities/user/types";
import type { ServiceAccessException, ServiceGrant } from "../../entities/access/types";

const now = "2026-05-01T09:00:00Z";

export const mockClients: Client[] = [
  {
    id: "client_romashka",
    type: "company",
    name: "DCTOUCH",
    legalName: "ООО ДИСИТАЧ",
    status: "active",
    contractStartsAt: "2026-05-04T00:00:00.000Z",
    contractEndsAt: null,
    paidUntil: null,
    demoEndsAt: null,
    contactName: "DC Touch",
    contactEmail: "dcctouch@gmail.com",
    avatarUrl: null,
    notes: "Live-клиент NODE.DC для первичной проверки control-plane, SSO и доступа к сервисам.",
    createdAt: "2026-05-04T00:00:00.000Z",
    updatedAt: now,
  },
];

export const mockUsers: LauncherUser[] = [
  {
    id: "user_root",
    authentikUserId: null,
    name: "DC Touch",
    email: "dcctouch@gmail.com",
    phone: null,
    position: "NODE.DC Super Admin",
    notes: "Главный супер-администратор NODE.DC.",
    avatarUrl: null,
    globalStatus: "active",
    createdAt: "2026-05-04T00:00:00.000Z",
    updatedAt: now,
  },
  {
    id: "user_silver_psih",
    authentikUserId: null,
    name: "Silver Psy",
    email: "silver_psih@yahoo.com",
    phone: null,
    position: "Manager",
    notes: "Живой пользователь из Plane. Требует Authentik invite/sync flow.",
    avatarUrl: null,
    globalStatus: "active",
    createdAt: "2026-05-04T00:00:00.000Z",
    updatedAt: now,
  },
];

export const mockMemberships: ClientMembership[] = [
  membership("mem_dc_touch_dctouch", "client_romashka", "user_root", "client_owner"),
  membership("mem_silver_psih_dctouch", "client_romashka", "user_silver_psih", "member"),
];

export const mockGroups: ClientGroup[] = [
  group("group_dctouch_admins", "client_romashka", "Администраторы", "Администраторы клиента и владельцы платформенного доступа.", [
    "user_root",
  ]),
  group("group_dctouch_managers", "client_romashka", "Менеджеры", "Рабочая группа менеджеров с доступом к операционному контуру.", [
    "user_silver_psih",
  ]),
];

export const mockServices: Service[] = [
  {
    id: "service_nodedc",
    slug: "nodedc",
    title: "ENGINE",
    subtitle: "Агентная платформа",
    description: "Сборка, запуск и мониторинг агентных workflow.",
    fullDescription:
      "NodeDC используется для настройки агентных процессов, визуальной оркестрации, интеграций и runtime-мониторинга.",
    url: "https://engine.nodedc.ru/",
    launchUrl: "https://engine.nodedc.ru/",
    logoutUrl: "https://engine.nodedc.ru/logout",
    accentColor: "#B5FF5A",
    fallbackGradient: "linear-gradient(128deg, rgba(181, 255, 90, 0.84), rgba(37, 58, 36, 0.86) 42%, #0A0D10 82%)",
    status: "active",
    order: 10,
    authentikApplicationSlug: "nodedc-engine",
    authentikGroupName: "nodedc_viewer",
    createdAt: "2026-04-01T10:00:00Z",
    updatedAt: now,
  },
  {
    id: "service_task_manager",
    slug: "task-manager",
    title: "Task Manager",
    subtitle: "Операционный слой",
    description: "Задачи, контуры предприятия, процессы и AI-функции поверх задачника.",
    fullDescription: "Task Manager основан на архитектуре Plane и расширен AI-функциями NODE.DC.",
    url: "https://tasks.handhdc.ru/sso/launch",
    launchUrl: "https://tasks.handhdc.ru/sso/launch",
    accentColor: "#D7C8FF",
    fallbackGradient: "linear-gradient(132deg, rgba(215, 200, 255, 0.82), rgba(51, 41, 79, 0.9) 46%, #0B0D10 84%)",
    status: "active",
    order: 20,
    authentikApplicationSlug: "task-manager",
    authentikGroupName: "service-task-manager",
    createdAt: "2026-04-01T10:00:00Z",
    updatedAt: now,
  },
  {
    id: "service_bim_viewer",
    slug: "bim-viewer",
    title: "BIM VIEWER",
    subtitle: "BIM и CAD просмотр",
    description: "Персональный просмотр BIM/CAD моделей, версий и публичных ссылок.",
    fullDescription:
      "Standalone BIM/CAD viewer NODE.DC для рабочих моделей, вложений Operational Core, персонального модельного хранилища и безопасного внешнего просмотра по share-ссылкам.",
    url: "https://bim.nodedc.tech",
    launchUrl: "https://bim.nodedc.tech",
    logoutUrl: "https://bim.nodedc.tech/logout",
    accentColor: "#8FE3C8",
    fallbackGradient: "linear-gradient(132deg, rgba(143, 227, 200, 0.78), rgba(24, 70, 64, 0.9) 46%, #080B0F 84%)",
    status: "active",
    order: 25,
    authentikApplicationSlug: "bim-viewer",
    authentikGroupName: "nodedc:bim:access",
    isAvailableForAllNewClients: true,
    createdAt: "2026-06-18T00:00:00.000Z",
    updatedAt: now,
  },
  {
    id: "service_1c",
    slug: "1c-assistant",
    title: "1C Assistant",
    subtitle: "Бухгалтерский ассистент",
    description: "Вопросы к 1С, точные выборки и доказательная навигация по данным.",
    fullDescription: "Ассистент для бухгалтерских запросов, анализа операций, остатков и документов.",
    url: "https://1c.handhdc.ru/sso/launch",
    launchUrl: "https://1c.handhdc.ru/sso/launch",
    accentColor: "#8FD7FF",
    fallbackGradient: "linear-gradient(126deg, rgba(143, 215, 255, 0.8), rgba(32, 61, 80, 0.9) 44%, #080B0F 84%)",
    status: "maintenance",
    order: 30,
    authentikApplicationSlug: "1c-assistant",
    authentikGroupName: "service-1c-assistant",
    createdAt: "2026-04-01T10:00:00Z",
    updatedAt: now,
  },
  {
    id: "service_tender",
    slug: "tender-agent",
    title: "Tender Agent",
    subtitle: "Госзакупки и тендеры",
    description: "Поиск, анализ и подготовка тендерных решений.",
    fullDescription: "Сервис собирает тендерные данные, строит выжимку рисков и помогает подготовить пакет участия.",
    url: "https://tender.handhdc.ru/sso/launch",
    launchUrl: "https://tender.handhdc.ru/sso/launch",
    accentColor: "#FFD166",
    fallbackGradient: "linear-gradient(135deg, rgba(255, 209, 102, 0.84), rgba(74, 53, 19, 0.92) 42%, #0B0D10 86%)",
    status: "active",
    order: 40,
    authentikApplicationSlug: "tender-agent",
    authentikGroupName: "service-tender-agent",
    createdAt: "2026-04-03T10:00:00Z",
    updatedAt: now,
  },
  {
    id: "service_digital_twin",
    slug: "digital-twin",
    title: "Digital Twin",
    subtitle: "3D и пространственные данные",
    description: "Просмотр цифровых двойников, карт и объектных сцен.",
    fullDescription: "Витрина геометрии, объектов, слоёв и статусов инфраструктуры.",
    url: "https://twin.handhdc.ru/sso/launch",
    launchUrl: "https://twin.handhdc.ru/sso/launch",
    accentColor: "#76E4F7",
    fallbackGradient: "linear-gradient(140deg, rgba(118, 228, 247, 0.82), rgba(23, 69, 87, 0.92) 47%, #080B0F 86%)",
    status: "active",
    order: 50,
    authentikApplicationSlug: "digital-twin",
    authentikGroupName: "service-digital-twin",
    createdAt: "2026-04-05T10:00:00Z",
    updatedAt: now,
  },
  {
    id: "service_dm",
    slug: "digital-modules",
    title: "Digital Modules",
    subtitle: "Будущие модули",
    description: "Скрытый каталог модулей для root-admin preview.",
    fullDescription: "Площадка для будущих цифровых модулей NODE.DC.",
    url: "https://dm.handhdc.ru/sso/launch",
    launchUrl: "https://dm.handhdc.ru/sso/launch",
    accentColor: "#FF9AC2",
    fallbackGradient: "linear-gradient(135deg, rgba(255, 154, 194, 0.78), rgba(76, 41, 64, 0.9) 44%, #090B0F 86%)",
    status: "hidden",
    order: 60,
    authentikApplicationSlug: "digital-modules",
    authentikGroupName: "service-digital-modules",
    createdAt: "2026-04-10T10:00:00Z",
    updatedAt: now,
  },
  {
    id: "service_internal",
    slug: "internal-tools",
    title: "Internal Tools",
    subtitle: "Внутренний контур",
    description: "Отключённый сервис для проверки диагностики root-admin.",
    fullDescription: "Не показывается обычным пользователям, виден root-admin в каталоге.",
    url: "https://internal.handhdc.ru",
    launchUrl: "https://internal.handhdc.ru",
    accentColor: "#F97373",
    fallbackGradient: "linear-gradient(135deg, rgba(249, 115, 115, 0.78), rgba(73, 32, 32, 0.92) 43%, #090B0F 86%)",
    status: "disabled",
    order: 70,
    authentikApplicationSlug: "internal-tools",
    authentikGroupName: "service-internal-tools",
    createdAt: "2026-04-12T10:00:00Z",
    updatedAt: now,
  },
];

export const mockGrants: ServiceGrant[] = [
  grant("grant_dctouch_task_admins", "service_task_manager", "group", "group_dctouch_admins", "admin"),
  grant("grant_dctouch_task_managers", "service_task_manager", "group", "group_dctouch_managers", "member"),
  grant("grant_dctouch_nodedc_admins", "service_nodedc", "group", "group_dctouch_admins", "admin"),
  grant("grant_engine_user_silver_psih_yahoo_com", "service_nodedc", "user", "user_silver_psih", "member"),
  grant("grant_engine_user_constr_dc_yahoo_com", "service_nodedc", "user", "user_constr_dc_yahoo_com", "viewer"),
  grant("grant_bim_viewer_client_romashka", "service_bim_viewer", "client", "client_romashka", "member"),
  grant("grant_bim_viewer_client_public_pool", "service_bim_viewer", "client", "client_public_pool", "member"),
];

export const mockExceptions: ServiceAccessException[] = [];

export const mockInvites: Invite[] = [];

export const mockAccessRequests: AccessRequest[] = [];
export const mockTaskerInviteRequests: TaskerInviteRequest[] = [];
export const mockEngineWorkflowAccessRequests: EngineWorkflowAccessRequest[] = [];

export const mockSyncStatuses: SyncStatus[] = [
  sync("sync_dctouch_client_authentik", "client_romashka", "DCTOUCH", "client", "authentik", "synced"),
  sync("sync_dc_touch_authentik", "user_root", "dcctouch@gmail.com", "user", "authentik", "synced"),
  sync(
    "sync_silver_psih_authentik",
    "user_silver_psih",
    "silver_psih@yahoo.com",
    "user",
    "authentik",
    "pending",
    "Пользователь найден в Plane, но ещё не создан в Authentik через Launcher invite/sync flow."
  ),
  sync("sync_dctouch_groups_authentik", "client_romashka:groups", "DCTOUCH groups", "group", "authentik", "pending"),
  sync("sync_task_manager_authentik", "service_task_manager", "OPERATIONAL CORE", "service", "authentik", "synced"),
  sync("sync_bim_viewer_authentik", "service_bim_viewer", "BIM VIEWER", "service", "authentik", "pending"),
  sync(
    "sync_grant_bim_viewer_client_romashka",
    "grant_bim_viewer_client_romashka",
    "bim-viewer:client:client_romashka",
    "grant",
    "authentik",
    "pending"
  ),
  sync(
    "sync_grant_bim_viewer_client_public_pool",
    "grant_bim_viewer_client_public_pool",
    "bim-viewer:client:client_public_pool",
    "grant",
    "authentik",
    "pending"
  ),
];

export const mockAuditEvents: AuditEvent[] = [
  audit(
    "audit_live_seed_control_plane",
    "2026-05-04T00:00:00.000Z",
    "system",
    "NODE.DC seed",
    "Применён live seed control-plane",
    "control_plane",
    "Launcher users and access",
    "success",
    "Demo-участники удалены из runtime storage. Оставлены dcctouch@gmail.com и silver_psih@yahoo.com."
  ),
];

function membership(
  id: string,
  clientId: string,
  userId: string,
  role: ClientMembership["role"],
  status: ClientMembership["status"] = "active"
): ClientMembership {
  const coreAssistantRole: ClientMembership["coreAssistantRole"] = userId === "user_root" ? "admin" : "member";

  return {
    id,
    clientId,
    userId,
    role,
    status,
    coreAssistantRole,
    createdAt: "2026-04-01T10:00:00Z",
    updatedAt: now,
  };
}

function group(id: string, clientId: string, name: string, description: string, memberIds: string[]): ClientGroup {
  return {
    id,
    clientId,
    name,
    description,
    memberIds,
    createdAt: "2026-04-01T10:00:00Z",
    updatedAt: now,
  };
}

function grant(
  id: string,
  serviceId: string,
  targetType: ServiceGrant["targetType"],
  targetId: string,
  appRole: ServiceGrant["appRole"]
): ServiceGrant {
  return {
    id,
    serviceId,
    targetType,
    targetId,
    appRole,
    status: "active",
    createdAt: "2026-04-01T10:00:00Z",
    updatedAt: now,
  };
}

function sync(
  id: string,
  objectId: string,
  objectName: string,
  objectType: SyncStatus["objectType"],
  target: SyncStatus["target"],
  state: SyncStatus["state"],
  error: string | null = null
): SyncStatus {
  return {
    id,
    objectId,
    objectName,
    objectType,
    target,
    state,
    lastSyncAt: state === "pending" ? null : "2026-05-01T08:00:00Z",
    error,
    updatedAt: now,
  };
}

function audit(
  id: string,
  at: string,
  actorUserId: string,
  actorName: string,
  action: string,
  objectType: string,
  objectName: string,
  result: AuditEvent["result"],
  details: string | null,
  clientId: string | null = "client_romashka"
): AuditEvent {
  return {
    id,
    at,
    actorUserId,
    actorName,
    action,
    objectType,
    objectName,
    clientId,
    result,
    details,
  };
}
