export type AuthTokens = {
  superAdminAccessToken: string;
  superAdminRefreshToken: string;
};

export type ApiRole = "superadmin" | "admin" | "user";
export type SortOrder = "asc" | "desc";

export type ApiIdentifier = {
  _id?: string;
  id?: string;
};

export type PaginationMeta = {
  mode?: "offset" | "cursor";
  page: number;
  limit: number;
  count: number;
  total: number;
  totalPages: number;
  hasNextPage?: boolean;
  hasPreviousPage?: boolean;
  nextPage?: number | null;
  previousPage?: number | null;
  currentCursor?: string | null;
  nextCursor?: string | null;
};

export type PaginatedResponse<T> = {
  data?: T[];
  items?: T[];
  count?: number;
  total?: number;
  page?: number;
  limit?: number;
  totalPages?: number;
  nextCursor?: string | null;
  unreadCount?: number;
  pagination?: PaginationMeta;
};

export type ApiUser = {
  _id: string;
  name?: string;
  username?: string;
  email: string;
  role?: ApiRole;
  stageName?: string;
  bio?: string;
  location?: string;
  latitude?: number | null;
  longitude?: number | null;
  avatar?: string;
  coverImage?: string;
  musicRoles?: string[];
  musicGenres?: string[];
  favoriteInstruments?: string[];
  favoriteMaqamat?: string[];
  preferredMood?: string;
  experienceLevel?: string;
  isPrivate?: boolean;
  isDisabled?: boolean;
  isVerified?: boolean;
  disabledReason?: string;
  followersCount?: number;
  followingCount?: number;
  postsCount?: number;
  shopName?: string;
  shopDescription?: string;
  shopImageUrls?: string[];
  shopLocation?: string;
  shopLatitude?: number | null;
  shopLongitude?: number | null;
  createdAt?: string;
  updatedAt?: string;
};

export type UsersResponse = PaginatedResponse<ApiUser>;

export type AdminCreatePayload = {
  name?: string;
  username: string;
  email: string;
  password: string;
  confirmPassword: string;
};

export type AdminUpdatePayload = Partial<
  Pick<
    ApiUser,
    | "name"
    | "username"
    | "email"
    | "stageName"
    | "bio"
    | "location"
    | "avatar"
    | "coverImage"
    | "musicRoles"
    | "favoriteMaqamat"
    | "preferredMood"
    | "experienceLevel"
    | "favoriteInstruments"
    | "isPrivate"
    | "isVerified"
  >
>;

export type RolePayload = {
  role: ApiRole;
};

export type DisableUserPayload = {
  reason: string;
};

export type LoginResponse = {
  accessToken: string;
  refreshToken: string;
  user?: ApiUser;
  superAdmin?: { email: string };
};

export type SessionItem = {
  id?: string;
  jti?: string;
  createdAt?: string;
  expiresAt?: string;
  ip?: string;
  userAgent?: string;
};

export type SessionsResponse = {
  items: SessionItem[];
};

export type SuperAdminSessionResponse = {
  superAdmin: {
    email?: string;
  };
  permissions: string[];
  sessionStrategy?: string;
};

export type ApiPostType = "text" | "image" | "video" | "audio";
export type ApiPostVisibility = "public" | "followers" | "private";
export type ModerationStatus = "active" | "hidden" | "flagged";
export type MediaProcessingStatus = "pending" | "processing" | "ready" | "failed";

export type ApiPostMedia = {
  mediaType?: ApiPostType;
  displayUrl?: string;
  thumbnailUrl?: string;
  preferredPlaybackUrl?: string;
  hlsUrl?: string;
  videoUrl?: string;
  audioUrl?: string;
  durationSeconds?: number | null;
  isPlayable?: boolean;
};

export type ApiPost = {
  _id: string;
  id?: string;
  content: string;
  contentTop?: string;
  contentBottom?: string;
  visibility?: ApiPostVisibility;
  postType?: ApiPostType;
  imageUrls?: string[];
  imageVariants?: Record<string, string | undefined> | Array<Record<string, string | undefined>>;
  imageItems?: Array<{
    url?: string;
    caption?: string;
    altText?: string;
    order?: number;
    variants?: Record<string, string | undefined>;
  }>;
  videoUrl?: string;
  hlsUrl?: string;
  audioUrl?: string;
  thumbnailUrl?: string;
  thumbnailVariants?: Record<string, string | undefined>;
  durationSeconds?: number | null;
  processingStatus?: MediaProcessingStatus;
  media?: ApiPostMedia;
  style?: string;
  maqam?: string;
  rhythmSignature?: string;
  waveformPeaks?: number[];
  taggedUserIds?: ApiUser[];
  mentionUsernames?: string[];
  hashtags?: string[];
  moderationStatus?: ModerationStatus;
  moderationReason?: string;
  location?: string;
  latitude?: number | null;
  longitude?: number | null;
  likesCount?: number;
  commentsCount?: number;
  savesCount?: number;
  shareCount?: number;
  viewCount?: number;
  playCount?: number;
  likedByMe?: boolean;
  savedByMe?: boolean;
  followingAuthor?: boolean;
  isOwnPost?: boolean;
  canComment?: boolean;
  canMessage?: boolean;
  author?: ApiUser;
  authorId?: ApiUser | string;
  engagement?: {
    likesCount?: number;
    commentsCount?: number;
    savesCount?: number;
    shareCount?: number;
    viewCount?: number;
    playCount?: number;
  };
  createdAt?: string;
  updatedAt?: string;
};

export type PostsResponse = PaginatedResponse<ApiPost>;

export type ApiComment = {
  _id: string;
  postId: string;
  parentCommentId?: string;
  content: string;
  mentionUsernames?: string[];
  moderationStatus?: ModerationStatus;
  moderationReason?: string;
  createdAt?: string;
  updatedAt?: string;
  author?: ApiUser;
  authorId?: ApiUser | string;
};

export type CommentsResponse = PaginatedResponse<ApiComment>;

export type LikeStatusResponse = {
  liked?: boolean;
  success?: boolean;
};

export type SaveStatusResponse = {
  saved?: boolean;
  success?: boolean;
};

export type FollowStatusResponse = {
  following?: boolean;
  isFollowing?: boolean;
  isFollowedBy?: boolean;
  isMutual?: boolean;
};

export type FollowListItem = {
  _id?: string;
  user?: ApiUser;
  followerId?: ApiUser | string;
  followingId?: ApiUser | string;
  status?: "pending" | "accepted" | "rejected";
  createdAt?: string;
  updatedAt?: string;
};

export type FollowListResponse = PaginatedResponse<FollowListItem>;

export type PresenceResponse = {
  userId: string;
  isOnline: boolean;
  lastSeenAt?: string | null;
};

export type RegisterDevicePayload = {
  fcmToken: string;
  platform: "android" | "ios" | "web";
  deviceId?: string;
  appVersion?: string;
  locale?: string;
};

export type UnregisterDevicePayload = {
  fcmToken?: string;
  deviceId?: string;
};

export type DeviceItem = {
  _id: string;
  userId: string;
  fcmToken: string;
  platform: "android" | "ios" | "web";
  deviceId?: string;
  appVersion?: string;
  locale?: string;
  isActive?: boolean;
  lastSeenAt?: string;
  createdAt?: string;
  updatedAt?: string;
};

export type CollaborationRequestStatus = "pending" | "approved" | "rejected" | "cancelled";
export type CollaborationType = "duet" | "arrangement" | "composition";
export type CollaborationAttachmentType = "audio" | "demo" | "file";

export type CollaborationRequestItem = {
  _id?: string;
  id?: string;
  postId?: ApiPost | string | null;
  requesterId?: ApiUser | string;
  targetUserId?: ApiUser | string;
  requester?: ApiUser | null;
  targetUser?: ApiUser | null;
  post?: ApiPost | null;
  status: CollaborationRequestStatus;
  collaborationType?: CollaborationType | null;
  message?: string;
  attachmentUrl?: string;
  attachmentType?: CollaborationAttachmentType | null;
  createdAt?: string;
  updatedAt?: string;
};

export type CollaborationRequestsResponse = PaginatedResponse<CollaborationRequestItem>;

export type CollaborationRequestActionResponse = {
  approved?: boolean;
  rejected?: boolean;
  cancelled?: boolean;
  request: CollaborationRequestItem;
};

export type CollaborationRequestDetailResponse = {
  request: CollaborationRequestItem;
};

export type SuperAdminCollaborationRequestStatusPayload = {
  status: Exclude<CollaborationRequestStatus, "cancelled">;
  reason?: string;
};

export type MediaHealthStatus = "ok" | "warning" | "error";

export type MediaHealthResponse = {
  status: MediaHealthStatus;
  storage: {
    provider?: "local" | "s3";
    storageProvider?: "local" | "s3";
    basePath?: string;
    storageBasePath?: string;
    publicPath?: string;
    uploadsPublicPath?: string;
    publicBaseUrlConfigured?: boolean;
    publicBaseUrl?: string;
    storagePublicBaseUrlConfigured?: boolean;
    storagePublicBaseUrl?: string;
    isLocalStorage?: boolean;
    isS3Configured?: boolean;
    s3Configured?: boolean;
    uploadPathExists?: boolean;
    uploadPathReadable?: boolean;
    uploadPathWritable?: boolean;
    local?: Record<string, unknown>;
    s3?: {
      reachable?: boolean;
      bucket?: string;
      endpoint?: string;
      region?: string;
      forcePathStyle?: boolean;
      error?: string;
      [key: string]: unknown;
    };
  };
  processing: {
    imageProcessingEnabled: boolean;
    videoProcessingEnabled: boolean;
    videoHlsGenerationEnabled: boolean;
    videoThumbnailGenerationEnabled: boolean;
    maxVideoWidth: number;
    maxVideoFps: number;
    videoCrf: number;
    audioBitrateKbps: number;
    audioProcessingEnabled: boolean;
    ffmpegPath?: string;
    ffmpegAvailable: boolean;
    ffmpegVersion?: string;
    ffprobePath?: string;
    ffprobeAvailable: boolean;
    ffprobeVersion?: string;
    ffmpeg?: Record<string, unknown>;
    ffprobe?: Record<string, unknown>;
  };
  serving: {
    mediaAccessMode: "direct" | "signed" | string;
    signedUrlsEnabled: boolean;
    rangeRequests: boolean;
    immutableCacheSeconds: number;
    hlsManifestCacheSeconds: number;
    s3ImmutableCacheControl?: string;
    s3HlsManifestCacheControl?: string;
  };
  staticServing: {
    uploadsPublicPath: string;
    rangeRequestsExpected: boolean;
    cacheHeadersExpected: boolean;
    hlsMimeExpected: string;
  };
  warnings: string[];
};

export type NotificationType =
  | "like"
  | "comment"
  | "follow"
  | "message"
  | "save"
  | "share"
  | "mention"
  | "reply"
  | "system"
  | "collaboration_request";

export type NotificationItem = {
  _id: string;
  type: NotificationType;
  title?: string;
  previewText?: string;
  body?: string;
  read?: boolean;
  resourceType?: string;
  deepLink?: string;
  metadata?: Record<string, unknown>;
  referenceId?: string;
  actorId?: ApiUser | string;
  recipientId?: string;
  createdAt?: string;
  updatedAt?: string;
};

export type NotificationsResponse = PaginatedResponse<NotificationItem>;

export type ReportTargetType = "user" | "post" | "comment" | "listing" | "repair_shop";
export type ReportStatus = "open" | "in_review" | "resolved" | "rejected";
export type ReportReason =
  | "spam"
  | "harassment"
  | "hate_speech"
  | "nudity"
  | "violence"
  | "scam"
  | "intellectual_property"
  | "self_harm"
  | "other";

export type PlatformReport = {
  _id: string;
  reporterId?: ApiUser | string;
  targetType: ReportTargetType;
  targetId: string;
  reason: ReportReason;
  details?: string;
  status: ReportStatus;
  resolutionNote?: string;
  resolvedBy?: string;
  resolvedAt?: string | null;
  createdAt?: string;
  updatedAt?: string;
};

export type ReportsResponse = PaginatedResponse<PlatformReport>;

export type SupportTicketCategory =
  | "account"
  | "technical"
  | "media"
  | "payment"
  | "collaboration"
  | "other";

export type SupportTicketPriority = "low" | "normal" | "high" | "urgent";
export type SupportTicketStatus = "open" | "pending" | "in_progress" | "resolved" | "closed";
export type SupportSenderRole = "user" | "admin" | "superadmin" | "system";

export type SupportTicket = {
  _id: string;
  userId: string;
  assignedAdminId?: string | null;
  user?: ApiUser | null;
  assignedAdmin?: ApiUser | null;
  subject: string;
  category: SupportTicketCategory;
  priority: SupportTicketPriority;
  status: SupportTicketStatus;
  lastMessageAt?: string;
  resolvedAt?: string | null;
  closedAt?: string | null;
  createdAt?: string;
  updatedAt?: string;
};

export type SupportTicketMessage = {
  _id: string;
  ticketId: string;
  senderId?: string | null;
  senderIdentifier?: string;
  sender?: ApiUser | null;
  senderRole: SupportSenderRole;
  message?: string;
  attachmentUrl?: string;
  attachmentType?: "image" | "file" | null;
  readByUser?: boolean;
  readByAdmin?: boolean;
  createdAt?: string;
  updatedAt?: string;
};

export type SupportTicketsResponse = PaginatedResponse<SupportTicket>;

export type SupportTicketDetailResponse = {
  ticket: SupportTicket;
  messages: SupportTicketMessage[];
};

export type SupportTicketUpdateResponse = {
  message?: string;
  item: SupportTicket;
};

export type SupportMessageResponse = {
  message?: string;
  item: SupportTicketMessage;
};

export type Conversation = {
  _id: string;
  isGroup?: boolean;
  participantIds?: string[];
  createdAt?: string;
  updatedAt?: string;
};

export type Message = {
  _id: string;
  conversationId: string;
  messageType: string;
  content: string;
  mediaUrl?: string;
  createdAt?: string;
};

export type ConversationsResponse = PaginatedResponse<Conversation>;
export type MessagesResponse = PaginatedResponse<Message>;

export type ChatBlockStatus = {
  iBlocked: boolean;
  blockedMe: boolean;
};

export type FeedItemType = "post" | "suggested_users" | "featured_marketplace";

export type FeedItem = {
  _id: string;
  feedItemType?: FeedItemType;
  post?: ApiPost;
  user?: ApiUser;
  score?: number;
  items?: unknown[];
};

export type FeedResponse = PaginatedResponse<FeedItem>;

export type MarketplaceListingCategory =
  | "musical_instrument"
  | "accessory"
  | "audio_gear"
  | "sheet_music"
  | "other";

export type MarketplaceListingCondition = "new" | "used" | "like_new" | "refurbished";

export type MarketplaceShopSummary = {
  adminId?: string;
  name?: string;
  username?: string;
  avatar?: string;
};

export type MarketplaceListing = {
  _id: string;
  title: string;
  description?: string;
  price: number;
  currency?: string;
  quantity?: number;
  imageUrls?: string[];
  isActive?: boolean;
  listingCategory?: MarketplaceListingCategory;
  condition?: MarketplaceListingCondition;
  instrumentType?: string;
  ownerAdminId?: ApiUser | string;
  shop?: MarketplaceShopSummary;
  storeName?: string;
  createdAt?: string;
  updatedAt?: string;
};

export type MarketplaceRepairShop = {
  _id: string;
  name: string;
  description?: string;
  services?: string[];
  phone?: string;
  whatsapp?: string;
  imageUrls?: string[];
  location?: string;
  latitude?: number | null;
  longitude?: number | null;
  isActive?: boolean;
  ownerAdminId?: ApiUser | string;
  shop?: MarketplaceShopSummary;
  storeName?: string;
  createdAt?: string;
  updatedAt?: string;
};

export type MarketplaceShopProfile = {
  adminId: string;
  adminName?: string;
  adminUsername?: string;
  adminEmail?: string;
  shopName?: string;
  shopDescription?: string;
  shopImageUrls?: string[];
  shopLocation?: string;
  shopLatitude?: number | null;
  shopLongitude?: number | null;
  isDisabled?: boolean;
  createdAt?: string;
  updatedAt?: string;
};

export type MarketplaceResponse = PaginatedResponse<MarketplaceListing>;
export type MarketplaceRepairShopResponse = PaginatedResponse<MarketplaceRepairShop>;

export type MarketplaceHomeResponse = {
  categories: Array<{ key: string; title: string; endpoint: string }>;
  summary: {
    activeListings: number;
    activeMusicalInstruments: number;
    activeRepairShops: number;
  };
  filters: {
    listingCategories: Array<{ key: string; count: number }>;
  };
  featuredShops: MarketplaceShopProfile[];
  sections: {
    listings: MarketplaceResponse & { title: string; endpoint: string };
    musicalInstruments: MarketplaceResponse & { title: string; endpoint: string };
    repairShops: MarketplaceRepairShopResponse & { title: string; endpoint: string };
  };
};

export type TalentRoleBucket = {
  role: string;
  count: number;
};

export type TalentDiscoverResponse = UsersResponse & {
  roleBuckets?: TalentRoleBucket[];
  activeRole?: string | null;
};

export type ProfileOverviewResponse = {
  user: ApiUser;
  stats: {
    followersCount: number;
    followingCount: number;
    postsCount: number;
    collaborationsCount: number;
  };
  contentCounts: {
    reels: number;
    audio: number;
    image: number;
    text: number;
    other: number;
  };
  tabs: Array<{ key: string; postType?: ApiPostType; count: number }>;
  viewerState: {
    isOwnProfile: boolean;
    following: boolean;
    canMessage: boolean;
  };
};

export type AuditLogItem = {
  _id: string;
  actorType: "user" | "superadmin" | "system";
  actorUserId?: string;
  actorIdentifier?: string;
  action: string;
  targetType: string;
  targetId?: string;
  metadata?: Record<string, unknown>;
  createdAt?: string;
  updatedAt?: string;
};

export type AuditLogsResponse = PaginatedResponse<AuditLogItem>;

export type CounterResponse = {
  success?: boolean;
  postId?: string;
  viewCount?: number;
  playCount?: number;
  shareCount?: number;
};

export type SuccessMessage = {
  success?: boolean;
  message?: string;
  updatedCount?: number;
  unreadCount?: number;
};

export type SuperAdminOverviewResponse = {
  metrics: {
    usersCount: number;
    adminsCount: number;
    disabledUsersCount: number;
    postsCount: number;
    hiddenPostsCount: number;
    flaggedPostsCount: number;
    commentsCount: number;
    hiddenCommentsCount: number;
    flaggedCommentsCount: number;
    marketplaceListingsCount: number;
    musicalInstrumentsCount: number;
    generalMarketplaceListingsCount: number;
    inactiveListingsCount: number;
    repairShopsCount: number;
    inactiveRepairShopsCount: number;
    unreadNotificationsCount: number;
    openCasesCount: number;
    inReviewCasesCount: number;
    failedOutboxEventsCount: number;
    pendingOutboxEventsCount: number;
    activeSuperAdminSessionsCount: number;
  };
};

export type SuperAdminChartPoint = {
  date: string;
  label: string;
  count: number;
};

export type SuperAdminBreakdownItem = {
  label: string;
  value: number;
};

export type SuperAdminChartsResponse = {
  range: "7d" | "30d" | "90d";
  days: number;
  series: {
    users: SuperAdminChartPoint[];
    posts: SuperAdminChartPoint[];
    comments: SuperAdminChartPoint[];
    listings: SuperAdminChartPoint[];
    repairShops: SuperAdminChartPoint[];
    notifications: SuperAdminChartPoint[];
  };
  breakdowns: {
    userRoles: SuperAdminBreakdownItem[];
    postTypes: SuperAdminBreakdownItem[];
    listingCategories: SuperAdminBreakdownItem[];
    moderation: SuperAdminBreakdownItem[];
  };
  kpis?: {
    activeSuperAdminSessionsCount: number;
    moderationQueueCount: number;
    failedOutboxEventsCount: number;
    pendingOutboxEventsCount: number;
  };
};

export type SuperAdminRecentActivityItem = {
  type: string;
  action: string;
  title: string;
  subtitle: string;
  status: string;
  deepLink: string;
  createdAt?: string;
};

export type SuperAdminRecentActivityResponse = {
  items: SuperAdminRecentActivityItem[];
};

export type SuperAdminReportsResponse = {
  summary: {
    flaggedPostsCount: number;
    flaggedCommentsCount: number;
    disabledUsersCount: number;
    inactiveListingsCount: number;
    inactiveRepairShopsCount: number;
    openCasesCount: number;
    failedOutboxEventsCount: number;
    pendingOutboxEventsCount: number;
  };
  flaggedPosts: ApiPost[];
  flaggedComments: ApiComment[];
  disabledUsers: ApiUser[];
  inactiveListings: MarketplaceListing[];
  inactiveRepairShops: MarketplaceRepairShop[];
};

export type SuperAdminSettings = {
  scope?: string;
  siteName: string;
  publicBaseUrl: string;
  dashboardApiBaseUrl: string;
  corsOrigins: string[];
  maintenanceMode: boolean;
  emailEnabled: boolean;
  marketplaceAutoApprove: boolean;
  contentAutoHideFlagged: boolean;
  notes: string;
  updatedBy?: string;
  updatedAt?: string;
  createdAt?: string;
};

export type SuperAdminSettingsResponse = {
  settings: SuperAdminSettings;
  historySummary?: {
    lastUpdatedBy?: string;
    lastChangedFields?: string[];
    lastUpdatedAt?: string;
  } | null;
  runtime: {
    nodeEnv?: string;
    host?: string;
    port?: number;
    globalPrefix?: string;
    publicBaseUrl?: string;
    responseEnvelopeEnabled?: boolean;
    emailEnabled?: boolean;
    corsOrigins?: string[];
    swaggerPath?: string;
    storageProvider?: string;
    storageBasePath?: string;
    queueEnabled?: boolean;
    redisEnabled?: boolean;
    sessionStrategy?: string;
  };
};

export type SuperAdminSettingsHistoryEntry = {
  _id: string;
  scope: string;
  updatedBy: string;
  changedFields: string[];
  previousSettings: Record<string, unknown>;
  nextSettings: Record<string, unknown>;
  note?: string;
  createdAt?: string;
};

export type SuperAdminSettingsHistoryResponse = PaginatedResponse<SuperAdminSettingsHistoryEntry>;

export type SuperAdminCaseStatus = "open" | "in_review" | "resolved";
export type SuperAdminCasePriority = "low" | "normal" | "high" | "critical";

export type CreateSuperAdminCasePayload = {
  title: string;
  description?: string;
  caseType?: string;
  resourceType: string;
  resourceId?: string;
  priority?: SuperAdminCasePriority;
  assignedTo?: string;
  tags?: string[];
};

export type SuperAdminCase = {
  _id: string;
  title: string;
  description?: string;
  caseType: string;
  resourceType: string;
  resourceId?: string;
  status: SuperAdminCaseStatus;
  priority: SuperAdminCasePriority;
  assignedTo?: string;
  createdBy?: string;
  updatedBy?: string;
  tags?: string[];
  resolution?: string;
  events?: Array<{
    action: string;
    actor: string;
    note?: string;
    createdAt?: string;
  }>;
  createdAt?: string;
  updatedAt?: string;
};

export type SuperAdminCasesResponse = PaginatedResponse<SuperAdminCase>;

export type SuperAdminOpsResponse = {
  services: {
    mongodb: {
      status: string;
      database?: string;
    };
    redis: {
      enabled: boolean;
      status: string;
    };
    queue: {
      enabled: boolean;
      name?: string;
    };
    storage: {
      provider?: string;
      basePath?: string;
    };
    email: {
      enabled: boolean;
    };
    websocket: {
      redisAdapterEnabled: boolean;
    };
  };
  queues: {
    outbox: {
      pending: number;
      failed: number;
    };
  };
  workload: {
    openCasesCount: number;
    activeSuperAdminSessionsCount: number;
  };
};
