import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectConnection, InjectModel } from '@nestjs/mongoose';
import { Connection, Model, Types } from 'mongoose';
import { buildPaginatedResponse } from '../../common/utils/pagination.util';
import { resolveMongoSortDirection } from '../../common/utils/sort.util';
import { escapeRegex } from '../../common/utils/regex.util';
import { ModerationStatus } from '../../common/enums/moderation-status.enum';
import { PaginationQueryDto } from '../../common/dto/pagination-query.dto';
import { FeedVersionService } from '../../infrastructure/cache/feed-version.service';
import { RedisService } from '../../infrastructure/redis/redis.service';
import { ManagedStorageService } from '../../infrastructure/storage/managed-storage.service';
import { AuditService } from '../audit/audit.service';
import { AuditLog, AuditLogDocument } from '../audit/schemas/audit-log.schema';
import { CommentsService } from '../comments/comments.service';
import { Comment, CommentDocument } from '../comments/schemas/comment.schema';
import { SuperAdminRefreshToken, SuperAdminRefreshTokenDocument } from '../auth/schemas/super-admin-refresh-token.schema';
import { Instrument, InstrumentDocument } from '../marketplace/schemas/instrument.schema';
import { RepairShop, RepairShopDocument } from '../marketplace/schemas/repair-shop.schema';
import { Notification, NotificationDocument } from '../notifications/schemas/notification.schema';
import { OutboxEvent, OutboxEventDocument } from '../outbox/schemas/outbox-event.schema';
import { PostsService } from '../posts/posts.service';
import { Post, PostDocument } from '../posts/schemas/post.schema';
import { UsersService } from '../users/users.service';
import { User, UserDocument } from '../users/schemas/user.schema';
import { BulkSuperAdminActionDto } from './dto/bulk-superadmin-action.dto';
import { CreateSuperAdminCaseDto } from './dto/create-superadmin-case.dto';
import { SuperAdminCaseQueryDto } from './dto/superadmin-case-query.dto';
import { SuperAdminChartsQueryDto } from './dto/superadmin-charts-query.dto';
import { SuperAdminRecentActivityQueryDto } from './dto/superadmin-recent-activity-query.dto';
import { SuperAdminReportsQueryDto } from './dto/superadmin-reports-query.dto';
import { UpdateContentModerationStatusDto } from './dto/update-content-moderation-status.dto';
import { UpdateSuperAdminCaseDto } from './dto/update-superadmin-case.dto';
import { UpdateSuperAdminSettingsDto } from './dto/update-superadmin-settings.dto';
import { UpdateSuperAdminUserStatusDto } from './dto/update-superadmin-user-status.dto';
import { DEFAULT_SUPERADMIN_PERMISSIONS } from './superadmin-permissions';
import { SuperAdminCase, SuperAdminCaseDocument } from './schemas/superadmin-case.schema';
import {
  SuperAdminSettings,
  SuperAdminSettingsDocument,
} from './schemas/superadmin-settings.schema';
import {
  SuperAdminSettingsHistory,
  SuperAdminSettingsHistoryDocument,
} from './schemas/superadmin-settings-history.schema';

type CaseStatus = 'open' | 'in_review' | 'resolved';
type CasePriority = 'low' | 'normal' | 'high' | 'critical';

@Injectable()
export class SuperAdminService {
  private readonly defaultSettingsScope = 'default';

  constructor(
    @InjectConnection() private readonly connection: Connection,
    @InjectModel(User.name) private readonly userModel: Model<UserDocument>,
    @InjectModel(Post.name) private readonly postModel: Model<PostDocument>,
    @InjectModel(Comment.name) private readonly commentModel: Model<CommentDocument>,
    @InjectModel(Instrument.name) private readonly instrumentModel: Model<InstrumentDocument>,
    @InjectModel(RepairShop.name) private readonly repairShopModel: Model<RepairShopDocument>,
    @InjectModel(Notification.name)
    private readonly notificationModel: Model<NotificationDocument>,
    @InjectModel(AuditLog.name) private readonly auditLogModel: Model<AuditLogDocument>,
    @InjectModel(SuperAdminSettings.name)
    private readonly settingsModel: Model<SuperAdminSettingsDocument>,
    @InjectModel(SuperAdminSettingsHistory.name)
    private readonly settingsHistoryModel: Model<SuperAdminSettingsHistoryDocument>,
    @InjectModel(SuperAdminCase.name)
    private readonly superAdminCaseModel: Model<SuperAdminCaseDocument>,
    @InjectModel(OutboxEvent.name)
    private readonly outboxEventModel: Model<OutboxEventDocument>,
    @InjectModel(SuperAdminRefreshToken.name)
    private readonly superAdminRefreshTokenModel: Model<SuperAdminRefreshTokenDocument>,
    private readonly configService: ConfigService,
    private readonly auditService: AuditService,
    private readonly postsService: PostsService,
    private readonly commentsService: CommentsService,
    private readonly usersService: UsersService,
    private readonly redisService: RedisService,
    private readonly storageService: ManagedStorageService,
    private readonly feedVersionService: FeedVersionService,
  ) {}

  async getOverview(): Promise<Record<string, unknown>> {
    const musicalInstrumentFilter = this.buildMusicalInstrumentFilter();

    const [
      usersCount,
      adminsCount,
      disabledUsersCount,
      postsCount,
      hiddenPostsCount,
      flaggedPostsCount,
      commentsCount,
      hiddenCommentsCount,
      flaggedCommentsCount,
      allListingsCount,
      musicalInstrumentsCount,
      inactiveListingsCount,
      repairShopsCount,
      inactiveRepairShopsCount,
      unreadNotificationsCount,
      openCasesCount,
      inReviewCasesCount,
      failedOutboxEventsCount,
      pendingOutboxEventsCount,
      activeSuperAdminSessionsCount,
    ] = await Promise.all([
      this.userModel.countDocuments({ role: 'user' }).exec(),
      this.userModel.countDocuments({ role: 'admin' }).exec(),
      this.userModel.countDocuments({ isDisabled: true }).exec(),
      this.postModel.countDocuments({ isDeleted: { $ne: true } }).exec(),
      this.postModel
        .countDocuments({
          isDeleted: { $ne: true },
          moderationStatus: ModerationStatus.HIDDEN,
        })
        .exec(),
      this.postModel
        .countDocuments({
          isDeleted: { $ne: true },
          moderationStatus: ModerationStatus.FLAGGED,
        })
        .exec(),
      this.commentModel.countDocuments({ isDeleted: { $ne: true } }).exec(),
      this.commentModel
        .countDocuments({
          isDeleted: { $ne: true },
          moderationStatus: ModerationStatus.HIDDEN,
        })
        .exec(),
      this.commentModel
        .countDocuments({
          isDeleted: { $ne: true },
          moderationStatus: ModerationStatus.FLAGGED,
        })
        .exec(),
      this.instrumentModel.countDocuments({}).exec(),
      this.instrumentModel.countDocuments(musicalInstrumentFilter).exec(),
      this.instrumentModel.countDocuments({ isActive: false }).exec(),
      this.repairShopModel.countDocuments({}).exec(),
      this.repairShopModel.countDocuments({ isActive: false }).exec(),
      this.notificationModel.countDocuments({ read: false }).exec(),
      this.superAdminCaseModel.countDocuments({ status: 'open' }).exec(),
      this.superAdminCaseModel.countDocuments({ status: 'in_review' }).exec(),
      this.outboxEventModel.countDocuments({ status: 'failed' }).exec(),
      this.outboxEventModel.countDocuments({ status: 'pending' }).exec(),
      this.superAdminRefreshTokenModel
        .countDocuments({ revoked: false, expiresAt: { $gt: new Date() } })
        .exec(),
    ]);

    return {
      metrics: {
        usersCount,
        adminsCount,
        disabledUsersCount,
        postsCount,
        hiddenPostsCount,
        flaggedPostsCount,
        commentsCount,
        hiddenCommentsCount,
        flaggedCommentsCount,
        marketplaceListingsCount: allListingsCount,
        musicalInstrumentsCount,
        generalMarketplaceListingsCount: Math.max(0, allListingsCount - musicalInstrumentsCount),
        inactiveListingsCount,
        repairShopsCount,
        inactiveRepairShopsCount,
        unreadNotificationsCount,
        openCasesCount,
        inReviewCasesCount,
        failedOutboxEventsCount,
        pendingOutboxEventsCount,
        activeSuperAdminSessionsCount,
      },
    };
  }

  async getCharts(query: SuperAdminChartsQueryDto): Promise<Record<string, unknown>> {
    const range = query.range ?? '30d';
    const days = this.resolveRangeDays(range);
    const [users, posts, comments, listings, repairShops, notifications, activeSessions, openCases, failedOutbox, pendingOutbox] =
      await Promise.all([
        this.buildDailySeries(this.userModel, {}, days),
        this.buildDailySeries(this.postModel, { isDeleted: { $ne: true } }, days),
        this.buildDailySeries(this.commentModel, { isDeleted: { $ne: true } }, days),
        this.buildDailySeries(this.instrumentModel, {}, days),
        this.buildDailySeries(this.repairShopModel, {}, days),
        this.buildDailySeries(this.notificationModel, {}, days),
        this.superAdminRefreshTokenModel
          .countDocuments({ revoked: false, expiresAt: { $gt: new Date() } })
          .exec(),
        this.superAdminCaseModel.countDocuments({ status: { $in: ['open', 'in_review'] } }).exec(),
        this.outboxEventModel.countDocuments({ status: 'failed' }).exec(),
        this.outboxEventModel.countDocuments({ status: 'pending' }).exec(),
      ]);

    return {
      range,
      days,
      series: {
        users,
        posts,
        comments,
        listings,
        repairShops,
        notifications,
      },
      breakdowns: {
        userRoles: await this.buildUserRoleBreakdown(),
        postTypes: await this.buildPostTypeBreakdown(),
        listingCategories: await this.buildListingCategoryBreakdown(),
        moderation: [
          {
            label: 'flagged_posts',
            value: await this.postModel
              .countDocuments({ isDeleted: { $ne: true }, moderationStatus: ModerationStatus.FLAGGED })
              .exec(),
          },
          {
            label: 'hidden_posts',
            value: await this.postModel
              .countDocuments({ isDeleted: { $ne: true }, moderationStatus: ModerationStatus.HIDDEN })
              .exec(),
          },
          {
            label: 'flagged_comments',
            value: await this.commentModel
              .countDocuments({ isDeleted: { $ne: true }, moderationStatus: ModerationStatus.FLAGGED })
              .exec(),
          },
          {
            label: 'hidden_comments',
            value: await this.commentModel
              .countDocuments({ isDeleted: { $ne: true }, moderationStatus: ModerationStatus.HIDDEN })
              .exec(),
          },
        ],
      },
      kpis: {
        activeSuperAdminSessionsCount: activeSessions,
        moderationQueueCount: openCases,
        failedOutboxEventsCount: failedOutbox,
        pendingOutboxEventsCount: pendingOutbox,
      },
    };
  }

  async getRecentActivity(
    query: SuperAdminRecentActivityQueryDto,
  ): Promise<{ items: Array<Record<string, unknown>> }> {
    const limit = query.limit ?? 12;
    const batchLimit = Math.max(limit, 8);

    const [users, posts, comments, listings, repairShops, auditLogs, cases] = await Promise.all([
      this.userModel
        .find({})
        .sort({ createdAt: -1 })
        .limit(batchLimit)
        .select('name username email role isDisabled createdAt')
        .lean()
        .exec(),
      this.postModel
        .find({ isDeleted: { $ne: true } })
        .sort({ createdAt: -1 })
        .limit(batchLimit)
        .populate({ path: 'authorId', select: 'name username' })
        .select('content postType moderationStatus createdAt authorId')
        .lean()
        .exec(),
      this.commentModel
        .find({ isDeleted: { $ne: true } })
        .sort({ createdAt: -1 })
        .limit(batchLimit)
        .populate({ path: 'authorId', select: 'name username' })
        .select('content moderationStatus createdAt authorId')
        .lean()
        .exec(),
      this.instrumentModel
        .find({})
        .sort({ createdAt: -1 })
        .limit(batchLimit)
        .populate({ path: 'ownerAdminId', select: 'name username shopName' })
        .select('title listingCategory isActive createdAt ownerAdminId')
        .lean()
        .exec(),
      this.repairShopModel
        .find({})
        .sort({ createdAt: -1 })
        .limit(batchLimit)
        .populate({ path: 'ownerAdminId', select: 'name username shopName' })
        .select('name isActive location createdAt ownerAdminId')
        .lean()
        .exec(),
      this.auditLogModel
        .find({})
        .sort({ createdAt: -1 })
        .limit(batchLimit)
        .select('actorType actorIdentifier action targetType targetId createdAt')
        .lean()
        .exec(),
      this.superAdminCaseModel
        .find({})
        .sort({ updatedAt: -1, createdAt: -1 })
        .limit(batchLimit)
        .lean()
        .exec(),
    ]);

    const items = [
      ...users.map((user) => ({
        type: 'user',
        action: 'user_created',
        title: user.name || user.username || user.email,
        subtitle: `${user.email} - ${user.role}`,
        status: user.isDisabled ? 'disabled' : 'active',
        deepLink: '/users',
        createdAt: (user as any).createdAt,
      })),
      ...posts.map((post: any) => ({
        type: 'post',
        action: 'post_created',
        title: (post.content || '').slice(0, 80) || `${post.postType ?? 'post'} post`,
        subtitle: post.authorId?.name || post.authorId?.username || 'unknown author',
        status: post.moderationStatus ?? ModerationStatus.ACTIVE,
        deepLink: '/content',
        createdAt: post.createdAt,
      })),
      ...comments.map((comment: any) => ({
        type: 'comment',
        action: 'comment_created',
        title: (comment.content || '').slice(0, 80) || 'comment',
        subtitle: comment.authorId?.name || comment.authorId?.username || 'unknown author',
        status: comment.moderationStatus ?? ModerationStatus.ACTIVE,
        deepLink: '/content',
        createdAt: comment.createdAt,
      })),
      ...listings.map((listing: any) => ({
        type: 'listing',
        action: 'listing_created',
        title: listing.title,
        subtitle: `${listing.ownerAdminId?.shopName || listing.ownerAdminId?.name || 'shop'} - ${
          listing.listingCategory || 'listing'
        }`,
        status: listing.isActive ? 'active' : 'inactive',
        deepLink: '/marketplace',
        createdAt: listing.createdAt,
      })),
      ...repairShops.map((shop: any) => ({
        type: 'repair_shop',
        action: 'repair_shop_created',
        title: shop.name,
        subtitle: shop.location || shop.ownerAdminId?.shopName || shop.ownerAdminId?.name || 'repair shop',
        status: shop.isActive ? 'active' : 'inactive',
        deepLink: '/marketplace',
        createdAt: shop.createdAt,
      })),
      ...cases.map((item) => ({
        type: 'case',
        action: 'case_updated',
        title: item.title,
        subtitle: `${item.resourceType} - ${item.priority}`,
        status: item.status,
        deepLink: '/orders',
        createdAt: (item as any).updatedAt ?? (item as any).createdAt,
      })),
      ...auditLogs.map((audit) => ({
        type: 'audit',
        action: audit.action,
        title: audit.action,
        subtitle: `${audit.actorIdentifier || audit.actorType} - ${audit.targetType}`,
        status: audit.actorType,
        deepLink: '/security',
        createdAt: (audit as any).createdAt,
      })),
    ]
      .filter((item) => item.createdAt)
      .sort(
        (a, b) =>
          new Date(b.createdAt as string | Date).getTime() -
          new Date(a.createdAt as string | Date).getTime(),
      )
      .slice(0, limit);

    return { items };
  }

  async getReports(query: SuperAdminReportsQueryDto): Promise<Record<string, unknown>> {
    const limit = query.limit ?? 8;

    const [
      flaggedPosts,
      flaggedComments,
      disabledUsers,
      inactiveListings,
      inactiveRepairShops,
      flaggedPostsCount,
      flaggedCommentsCount,
      disabledUsersCount,
      inactiveListingsCount,
      inactiveRepairShopsCount,
      openCasesCount,
      failedOutboxEventsCount,
      pendingOutboxEventsCount,
    ] = await Promise.all([
      this.postModel
        .find({
          isDeleted: { $ne: true },
          moderationStatus: ModerationStatus.FLAGGED,
        })
        .sort({ updatedAt: -1, createdAt: -1 })
        .limit(limit)
        .populate({ path: 'authorId', select: 'name username avatar isVerified stageName' })
        .lean()
        .exec(),
      this.commentModel
        .find({
          isDeleted: { $ne: true },
          moderationStatus: ModerationStatus.FLAGGED,
        })
        .sort({ updatedAt: -1, createdAt: -1 })
        .limit(limit)
        .populate({ path: 'authorId', select: 'name username avatar stageName isVerified' })
        .lean()
        .exec(),
      this.userModel
        .find({ isDisabled: true })
        .sort({ disabledAt: -1, updatedAt: -1, createdAt: -1 })
        .limit(limit)
        .lean()
        .exec(),
      this.instrumentModel
        .find({ isActive: false })
        .sort({ updatedAt: -1, createdAt: -1 })
        .limit(limit)
        .populate({ path: 'ownerAdminId', select: 'name username email avatar isDisabled shopName' })
        .lean()
        .exec(),
      this.repairShopModel
        .find({ isActive: false })
        .sort({ updatedAt: -1, createdAt: -1 })
        .limit(limit)
        .populate({ path: 'ownerAdminId', select: 'name username email avatar isDisabled shopName' })
        .lean()
        .exec(),
      this.postModel
        .countDocuments({
          isDeleted: { $ne: true },
          moderationStatus: ModerationStatus.FLAGGED,
        })
        .exec(),
      this.commentModel
        .countDocuments({
          isDeleted: { $ne: true },
          moderationStatus: ModerationStatus.FLAGGED,
        })
        .exec(),
      this.userModel.countDocuments({ isDisabled: true }).exec(),
      this.instrumentModel.countDocuments({ isActive: false }).exec(),
      this.repairShopModel.countDocuments({ isActive: false }).exec(),
      this.superAdminCaseModel.countDocuments({ status: { $in: ['open', 'in_review'] } }).exec(),
      this.outboxEventModel.countDocuments({ status: 'failed' }).exec(),
      this.outboxEventModel.countDocuments({ status: 'pending' }).exec(),
    ]);

    return {
      summary: {
        flaggedPostsCount,
        flaggedCommentsCount,
        disabledUsersCount,
        inactiveListingsCount,
        inactiveRepairShopsCount,
        openCasesCount,
        failedOutboxEventsCount,
        pendingOutboxEventsCount,
      },
      flaggedPosts,
      flaggedComments,
      disabledUsers,
      inactiveListings,
      inactiveRepairShops,
    };
  }

  getSession(currentUser: { email?: string; permissions?: string[] }): Record<string, unknown> {
    return {
      superAdmin: {
        email: currentUser.email ?? this.configService.get<string>('superAdmin.email', { infer: true }),
      },
      permissions: currentUser.permissions ?? DEFAULT_SUPERADMIN_PERMISSIONS,
      sessionStrategy: 'httpOnly_cookies',
    };
  }

  async getCases(query: SuperAdminCaseQueryDto): Promise<Record<string, unknown>> {
    const page = query.page ?? 1;
    const limit = query.limit ?? 20;
    const skip = (page - 1) * limit;
    const filter: Record<string, unknown> = {};

    if (query.q?.trim()) {
      filter.$or = [
        { title: { $regex: escapeRegex(query.q.trim()), $options: 'i' } },
        { description: { $regex: escapeRegex(query.q.trim()), $options: 'i' } },
        { resourceId: { $regex: escapeRegex(query.q.trim()), $options: 'i' } },
        { assignedTo: { $regex: escapeRegex(query.q.trim()), $options: 'i' } },
        { resourceType: { $regex: escapeRegex(query.q.trim()), $options: 'i' } },
      ];
    }

    if (query.status) {
      filter.status = query.status;
    }
    if (query.priority) {
      filter.priority = query.priority;
    }
    if (query.resourceType?.trim()) {
      filter.resourceType = query.resourceType.trim();
    }
    if (query.assignedTo?.trim()) {
      filter.assignedTo = query.assignedTo.trim();
    }

    const sort = { updatedAt: resolveMongoSortDirection(query.sortOrder) } as Record<string, 1 | -1>;
    const [items, total] = await Promise.all([
      this.superAdminCaseModel.find(filter).sort(sort).skip(skip).limit(limit).lean().exec(),
      this.superAdminCaseModel.countDocuments(filter).exec(),
    ]);

    return buildPaginatedResponse(items, {
      page,
      limit,
      total,
      offset: skip,
    });
  }

  async createCase(
    superAdminIdentifier: string,
    dto: CreateSuperAdminCaseDto,
  ): Promise<SuperAdminCaseDocument> {
    const item = await this.superAdminCaseModel.create({
      title: dto.title.trim(),
      description: dto.description?.trim() ?? '',
      caseType: dto.caseType.trim(),
      resourceType: dto.resourceType.trim(),
      resourceId: dto.resourceId?.trim() ?? '',
      status: dto.status ?? 'open',
      priority: dto.priority ?? 'normal',
      assignedTo: dto.assignedTo?.trim() ?? '',
      createdBy: superAdminIdentifier,
      updatedBy: superAdminIdentifier,
      tags: dto.tags ?? [],
      events: [
        {
          action: 'case_created',
          actor: superAdminIdentifier,
          note: dto.note?.trim() ?? '',
          metadata: {},
          createdAt: new Date(),
        },
      ],
    });

    await this.auditService.logSuperAdminAction(
      superAdminIdentifier,
      'superadmin_case_create',
      'superadmin_case',
      item.id,
      {
        resourceType: item.resourceType,
        resourceId: item.resourceId,
      },
    );

    return item;
  }

  async updateCase(
    superAdminIdentifier: string,
    caseId: string,
    dto: UpdateSuperAdminCaseDto,
  ): Promise<SuperAdminCaseDocument> {
    const current = await this.superAdminCaseModel.findById(caseId).exec();
    if (!current) {
      throw new NotFoundException('Case not found');
    }

    const payload: Record<string, unknown> = {
      updatedBy: superAdminIdentifier,
    };

    if (typeof dto.title === 'string') payload.title = dto.title.trim();
    if (typeof dto.description === 'string') payload.description = dto.description.trim();
    if (typeof dto.caseType === 'string') payload.caseType = dto.caseType.trim();
    if (typeof dto.resourceType === 'string') payload.resourceType = dto.resourceType.trim();
    if (typeof dto.resourceId === 'string') payload.resourceId = dto.resourceId.trim();
    if (typeof dto.status === 'string') payload.status = dto.status;
    if (typeof dto.priority === 'string') payload.priority = dto.priority;
    if (typeof dto.assignedTo === 'string') payload.assignedTo = dto.assignedTo.trim();
    if (Array.isArray(dto.tags)) payload.tags = dto.tags;
    if (typeof dto.note === 'string') payload.resolution = dto.note.trim();

    const updated = await this.superAdminCaseModel
      .findByIdAndUpdate(
        caseId,
        {
          ...payload,
          $push: {
            events: {
              action: 'case_updated',
              actor: superAdminIdentifier,
              note: dto.note?.trim() ?? '',
              metadata: {
                fields: Object.keys(dto),
              },
              createdAt: new Date(),
            },
          },
        },
        { new: true },
      )
      .exec();

    if (!updated) {
      throw new NotFoundException('Case not found');
    }

    await this.auditService.logSuperAdminAction(
      superAdminIdentifier,
      'superadmin_case_update',
      'superadmin_case',
      caseId,
      {
        fields: Object.keys(dto),
        previousStatus: current.status,
        nextStatus: updated.status,
      },
    );

    return updated;
  }

  async performBulkAction(
    superAdminIdentifier: string,
    dto: BulkSuperAdminActionDto,
  ): Promise<Record<string, unknown>> {
    const items: Array<Record<string, unknown>> = [];

    for (const targetId of dto.targetIds) {
      try {
        await this.performSingleBulkAction(superAdminIdentifier, dto.resourceType, targetId, dto);
        await this.applyBulkCaseMetadata(superAdminIdentifier, dto.resourceType, targetId, dto);
        items.push({ id: targetId, success: true });
      } catch (error) {
        items.push({
          id: targetId,
          success: false,
          error: error instanceof Error ? error.message : 'unknown error',
        });
      }
    }

    const succeeded = items.filter((item) => item.success).length;
    const failed = items.length - succeeded;

    await this.auditService.logSuperAdminAction(
      superAdminIdentifier,
      'superadmin_bulk_action',
      dto.resourceType,
      undefined,
      {
        action: dto.action,
        targetIds: dto.targetIds,
        succeeded,
        failed,
      },
    );

    return {
      resourceType: dto.resourceType,
      action: dto.action,
      total: dto.targetIds.length,
      succeeded,
      failed,
      items,
    };
  }

  async getSettings(): Promise<Record<string, unknown>> {
    const stored = await this.settingsModel.findOne({ scope: this.defaultSettingsScope }).lean().exec();
    const latestHistory = await this.settingsHistoryModel
      .findOne({ scope: this.defaultSettingsScope })
      .sort({ createdAt: -1 })
      .lean()
      .exec();

    return {
      settings: {
        ...this.buildDefaultSettings(),
        ...(stored ?? {}),
      },
      historySummary: latestHistory
        ? {
            lastUpdatedBy: latestHistory.updatedBy,
            lastChangedFields: latestHistory.changedFields,
            lastUpdatedAt: (latestHistory as any).createdAt,
          }
        : null,
      runtime: {
        nodeEnv: this.configService.get<string>('nodeEnv', { infer: true }),
        host: this.configService.get<string>('host', { infer: true }),
        port: this.configService.get<number>('port', { infer: true }),
        globalPrefix: this.configService.get<string>('globalPrefix', { infer: true }),
        publicBaseUrl: this.configService.get<string>('publicBaseUrl', { infer: true }),
        responseEnvelopeEnabled: this.configService.get<boolean>('responseEnvelopeEnabled', {
          infer: true,
        }),
        emailEnabled: this.configService.get<boolean>('email.enabled', { infer: true }),
        corsOrigins: this.configService.get<string[]>('cors.origins', { infer: true }) ?? [],
        swaggerPath: this.configService.get<string>('swagger.path', { infer: true }),
        storageProvider: this.configService.get<string>('storage.provider', { infer: true }),
        storageBasePath: this.configService.get<string>('storage.basePath', { infer: true }),
        queueEnabled: this.configService.get<boolean>('queue.enabled', { infer: true }) ?? false,
        redisEnabled: this.configService.get<boolean>('redis.enabled', { infer: true }) ?? false,
        sessionStrategy: 'httpOnly_cookies',
      },
    };
  }

  async getSettingsHistory(query: PaginationQueryDto) {
    const page = query.page ?? 1;
    const limit = query.limit ?? 20;
    const skip = (page - 1) * limit;
    const sort = { createdAt: resolveMongoSortDirection(query.sortOrder) } as Record<string, 1 | -1>;
    const [items, total] = await Promise.all([
      this.settingsHistoryModel
        .find({ scope: this.defaultSettingsScope })
        .sort(sort)
        .skip(skip)
        .limit(limit)
        .lean()
        .exec(),
      this.settingsHistoryModel.countDocuments({ scope: this.defaultSettingsScope }).exec(),
    ]);

    return buildPaginatedResponse(items, {
      page,
      limit,
      total,
      offset: skip,
    });
  }

  async restoreSettingsVersion(
    superAdminIdentifier: string,
    historyId: string,
  ): Promise<Record<string, unknown>> {
    const historyEntry = await this.settingsHistoryModel.findById(historyId).lean().exec();
    if (!historyEntry) {
      throw new NotFoundException('Settings history entry not found');
    }

    const previousSettings =
      (await this.settingsModel.findOne({ scope: this.defaultSettingsScope }).lean().exec()) ??
      this.buildDefaultSettings();
    const nextSettings = {
      ...(historyEntry.nextSettings ?? {}),
      scope: this.defaultSettingsScope,
      updatedBy: superAdminIdentifier,
    };

    await this.settingsModel
      .findOneAndUpdate(
        { scope: this.defaultSettingsScope },
        nextSettings,
        {
          new: true,
          upsert: true,
          setDefaultsOnInsert: true,
        },
      )
      .exec();

    await this.settingsHistoryModel.create({
      scope: this.defaultSettingsScope,
      updatedBy: superAdminIdentifier,
      changedFields: Object.keys(historyEntry.nextSettings ?? {}),
      previousSettings,
      nextSettings,
      note: `Restored from history ${historyId}`,
    });

    await this.auditService.logSuperAdminAction(
      superAdminIdentifier,
      'superadmin_settings_restore',
      'superadmin_settings_history',
      historyId,
    );

    return this.getSettings();
  }

  async getOps(): Promise<Record<string, unknown>> {
    const mongoStatuses = ['disconnected', 'connected', 'connecting', 'disconnecting'];
    let redisStatus = 'disabled';

    if (this.redisService.isEnabled()) {
      try {
        const client = this.redisService.getClient();
        redisStatus = (await client?.ping()) === 'PONG' ? 'connected' : 'degraded';
      } catch {
        redisStatus = 'unreachable';
      }
    }

    const [openCasesCount, failedOutboxEventsCount, pendingOutboxEventsCount, activeSuperAdminSessionsCount] =
      await Promise.all([
        this.superAdminCaseModel.countDocuments({ status: { $in: ['open', 'in_review'] } }).exec(),
        this.outboxEventModel.countDocuments({ status: 'failed' }).exec(),
        this.outboxEventModel.countDocuments({ status: 'pending' }).exec(),
        this.superAdminRefreshTokenModel
          .countDocuments({ revoked: false, expiresAt: { $gt: new Date() } })
          .exec(),
      ]);

    return {
      services: {
        mongodb: {
          status: mongoStatuses[this.connection.readyState] ?? 'unknown',
          database: this.connection.name,
        },
        redis: {
          enabled: this.redisService.isEnabled(),
          status: redisStatus,
        },
        queue: {
          enabled: this.configService.get<boolean>('queue.enabled', { infer: true }) ?? false,
          name: this.configService.get<string>('queue.name', { infer: true }) ?? 'app-jobs',
        },
        storage: {
          provider: this.configService.get<string>('storage.provider', { infer: true }) ?? 'local',
          basePath: this.configService.get<string>('storage.basePath', { infer: true }) ?? 'uploads',
        },
        email: {
          enabled: this.configService.get<boolean>('email.enabled', { infer: true }) ?? false,
        },
        websocket: {
          redisAdapterEnabled:
            this.configService.get<boolean>('redis.socketAdapterEnabled', { infer: true }) ?? false,
        },
      },
      queues: {
        outbox: {
          pending: pendingOutboxEventsCount,
          failed: failedOutboxEventsCount,
        },
      },
      workload: {
        openCasesCount,
        activeSuperAdminSessionsCount,
      },
    };
  }

  async updateSettings(
    superAdminIdentifier: string,
    dto: UpdateSuperAdminSettingsDto,
  ): Promise<Record<string, unknown>> {
    const previousSettings =
      (await this.settingsModel.findOne({ scope: this.defaultSettingsScope }).lean().exec()) ??
      this.buildDefaultSettings();
    const changedFields = Object.keys(dto);

    await this.settingsModel
      .findOneAndUpdate(
        { scope: this.defaultSettingsScope },
        {
          ...dto,
          scope: this.defaultSettingsScope,
          updatedBy: superAdminIdentifier,
        },
        {
          new: true,
          upsert: true,
          setDefaultsOnInsert: true,
        },
      )
      .exec();

    const nextSettings =
      (await this.settingsModel.findOne({ scope: this.defaultSettingsScope }).lean().exec()) ??
      this.buildDefaultSettings();

    await this.settingsHistoryModel.create({
      scope: this.defaultSettingsScope,
      updatedBy: superAdminIdentifier,
      changedFields,
      previousSettings,
      nextSettings,
      note: `Updated fields: ${changedFields.join(', ')}`,
    });

    await this.auditService.logSuperAdminAction(
      superAdminIdentifier,
      'superadmin_settings_update',
      'superadmin_settings',
      this.defaultSettingsScope,
      { fields: changedFields },
    );

    return this.getSettings();
  }

  async updatePostStatus(
    superAdminIdentifier: string,
    postId: string,
    dto: UpdateContentModerationStatusDto,
  ) {
    const post = await this.postsService.updateModerationStatusBySuperAdmin(
      superAdminIdentifier,
      postId,
      dto,
    );
    await this.recordResourceCase({
      actor: superAdminIdentifier,
      caseType: 'content_moderation',
      resourceType: 'post',
      resourceId: postId,
      title: this.buildContentCaseTitle('Post', (post as any)?.content ?? postId),
      description: dto.reason?.trim() ?? '',
      action: `post_status_${dto.status}`,
      note: dto.reason?.trim() ?? '',
      status: dto.status === ModerationStatus.ACTIVE ? 'resolved' : 'in_review',
      priority: dto.status === ModerationStatus.FLAGGED ? 'high' : 'normal',
    });
    return post;
  }

  async deletePost(superAdminIdentifier: string, postId: string) {
    const existing = await this.postModel.findById(postId).select('content isDeleted').lean().exec();
    if (!existing || (existing as any).isDeleted) {
      throw new NotFoundException('Post not found');
    }

    await this.postsService.removeBySuperAdmin(superAdminIdentifier, postId);
    await this.recordResourceCase({
      actor: superAdminIdentifier,
      caseType: 'content_moderation',
      resourceType: 'post',
      resourceId: postId,
      title: this.buildContentCaseTitle('Post', String((existing as any).content ?? postId)),
      description: 'Deleted by superadmin',
      action: 'post_deleted',
      note: 'Deleted by superadmin',
      status: 'resolved',
      priority: 'high',
    });

    return { success: true, postId };
  }

  async restorePost(superAdminIdentifier: string, postId: string) {
    const post = await this.postModel
      .findOne({ _id: new Types.ObjectId(postId), isDeleted: true })
      .select('+deletedAt +deletedBy')
      .exec();
    if (!post) {
      throw new NotFoundException('Deleted post not found');
    }

    post.isDeleted = false;
    post.deletedAt = null;
    post.deletedBy = null;
    await post.save();
    await this.userModel.findByIdAndUpdate(post.authorId, { $inc: { postsCount: 1 } }).exec();
    await this.feedVersionService.bumpGlobalVersion();

    await this.auditService.logSuperAdminAction(
      superAdminIdentifier,
      'post_restore',
      'post',
      postId,
    );

    await this.recordResourceCase({
      actor: superAdminIdentifier,
      caseType: 'content_moderation',
      resourceType: 'post',
      resourceId: postId,
      title: this.buildContentCaseTitle('Post', post.content ?? postId),
      description: 'Restored by superadmin',
      action: 'post_restored',
      note: 'Restored by superadmin',
      status: 'resolved',
      priority: 'normal',
    });

    const restored = await this.postModel
      .findById(postId)
      .populate({ path: 'authorId', select: 'name username avatar isVerified stageName' })
      .populate({ path: 'taggedUserIds', select: 'name username avatar stageName isVerified' })
      .exec();
    return restored;
  }

  async updateCommentStatus(
    superAdminIdentifier: string,
    commentId: string,
    dto: UpdateContentModerationStatusDto,
  ) {
    const comment = await this.commentsService.updateModerationStatusBySuperAdmin(
      superAdminIdentifier,
      commentId,
      dto,
    );
    await this.recordResourceCase({
      actor: superAdminIdentifier,
      caseType: 'content_moderation',
      resourceType: 'comment',
      resourceId: commentId,
      title: this.buildContentCaseTitle('Comment', (comment as any)?.content ?? commentId),
      description: dto.reason?.trim() ?? '',
      action: `comment_status_${dto.status}`,
      note: dto.reason?.trim() ?? '',
      status: dto.status === ModerationStatus.ACTIVE ? 'resolved' : 'in_review',
      priority: dto.status === ModerationStatus.FLAGGED ? 'high' : 'normal',
    });
    return comment;
  }

  async deleteComment(superAdminIdentifier: string, commentId: string) {
    const existing = await this.commentModel.findById(commentId).select('content isDeleted').lean().exec();
    if (!existing || (existing as any).isDeleted) {
      throw new NotFoundException('Comment not found');
    }

    await this.commentsService.removeBySuperAdmin(superAdminIdentifier, commentId);
    await this.recordResourceCase({
      actor: superAdminIdentifier,
      caseType: 'content_moderation',
      resourceType: 'comment',
      resourceId: commentId,
      title: this.buildContentCaseTitle('Comment', String((existing as any).content ?? commentId)),
      description: 'Deleted by superadmin',
      action: 'comment_deleted',
      note: 'Deleted by superadmin',
      status: 'resolved',
      priority: 'high',
    });

    return { success: true, commentId };
  }

  async restoreComment(superAdminIdentifier: string, commentId: string) {
    const comment = await this.commentModel
      .findOne({ _id: new Types.ObjectId(commentId), isDeleted: true })
      .select('+deletedAt +deletedBy')
      .exec();
    if (!comment) {
      throw new NotFoundException('Deleted comment not found');
    }

    comment.isDeleted = false;
    comment.deletedAt = null;
    comment.deletedBy = null;
    await comment.save();

    const totalComments = await this.commentModel
      .countDocuments({ postId: comment.postId, isDeleted: { $ne: true } })
      .exec();
    await this.postModel
      .findByIdAndUpdate(comment.postId, { commentsCount: totalComments })
      .exec();
    await this.feedVersionService.bumpGlobalVersion();

    await this.auditService.logSuperAdminAction(
      superAdminIdentifier,
      'comment_restore',
      'comment',
      commentId,
    );

    await this.recordResourceCase({
      actor: superAdminIdentifier,
      caseType: 'content_moderation',
      resourceType: 'comment',
      resourceId: commentId,
      title: this.buildContentCaseTitle('Comment', comment.content ?? commentId),
      description: 'Restored by superadmin',
      action: 'comment_restored',
      note: 'Restored by superadmin',
      status: 'resolved',
      priority: 'normal',
    });

    const restored = await this.commentModel
      .findById(commentId)
      .populate({ path: 'authorId', select: 'name username avatar stageName isVerified' })
      .exec();
    return restored;
  }

  async updateUserStatus(
    superAdminIdentifier: string,
    userId: string,
    dto: UpdateSuperAdminUserStatusDto,
  ) {
    const user = dto.isDisabled
      ? await this.usersService.disableUserBySuperAdmin(superAdminIdentifier, userId, {
          reason: dto.reason ?? 'Disabled via superadmin status endpoint',
        })
      : await this.usersService.enableUserBySuperAdmin(superAdminIdentifier, userId);

    await this.recordResourceCase({
      actor: superAdminIdentifier,
      caseType: 'user_review',
      resourceType: 'user',
      resourceId: userId,
      title: `User review: ${user.email ?? user.username ?? userId}`,
      description: dto.reason?.trim() ?? '',
      action: dto.isDisabled ? 'user_disabled' : 'user_enabled',
      note: dto.reason?.trim() ?? '',
      status: dto.isDisabled ? 'in_review' : 'resolved',
      priority: dto.isDisabled ? 'high' : 'normal',
    });

    return user;
  }

  private async performSingleBulkAction(
    superAdminIdentifier: string,
    resourceType: string,
    targetId: string,
    dto: BulkSuperAdminActionDto,
  ): Promise<void> {
    switch (resourceType) {
      case 'post':
        await this.performPostBulkAction(superAdminIdentifier, targetId, dto);
        return;
      case 'comment':
        await this.performCommentBulkAction(superAdminIdentifier, targetId, dto);
        return;
      case 'user':
        await this.performUserBulkAction(superAdminIdentifier, targetId, dto);
        return;
      case 'listing':
        await this.performListingBulkAction(superAdminIdentifier, targetId, dto);
        return;
      case 'repair_shop':
        await this.performRepairShopBulkAction(superAdminIdentifier, targetId, dto);
        return;
      default:
        throw new BadRequestException(`Unsupported bulk resource type "${resourceType}"`);
    }
  }

  private async performPostBulkAction(
    superAdminIdentifier: string,
    targetId: string,
    dto: BulkSuperAdminActionDto,
  ) {
    switch (dto.action) {
      case 'activate':
        await this.updatePostStatus(superAdminIdentifier, targetId, {
          status: ModerationStatus.ACTIVE,
          reason: dto.reason,
        });
        return;
      case 'flag':
        await this.updatePostStatus(superAdminIdentifier, targetId, {
          status: ModerationStatus.FLAGGED,
          reason: dto.reason,
        });
        return;
      case 'hide':
        await this.updatePostStatus(superAdminIdentifier, targetId, {
          status: ModerationStatus.HIDDEN,
          reason: dto.reason,
        });
        return;
      case 'delete':
        await this.deletePost(superAdminIdentifier, targetId);
        return;
      case 'restore':
        await this.restorePost(superAdminIdentifier, targetId);
        return;
      default:
        throw new BadRequestException(`Unsupported post action "${dto.action}"`);
    }
  }

  private async performCommentBulkAction(
    superAdminIdentifier: string,
    targetId: string,
    dto: BulkSuperAdminActionDto,
  ) {
    switch (dto.action) {
      case 'activate':
        await this.updateCommentStatus(superAdminIdentifier, targetId, {
          status: ModerationStatus.ACTIVE,
          reason: dto.reason,
        });
        return;
      case 'flag':
        await this.updateCommentStatus(superAdminIdentifier, targetId, {
          status: ModerationStatus.FLAGGED,
          reason: dto.reason,
        });
        return;
      case 'hide':
        await this.updateCommentStatus(superAdminIdentifier, targetId, {
          status: ModerationStatus.HIDDEN,
          reason: dto.reason,
        });
        return;
      case 'delete':
        await this.deleteComment(superAdminIdentifier, targetId);
        return;
      case 'restore':
        await this.restoreComment(superAdminIdentifier, targetId);
        return;
      default:
        throw new BadRequestException(`Unsupported comment action "${dto.action}"`);
    }
  }

  private async performUserBulkAction(
    superAdminIdentifier: string,
    targetId: string,
    dto: BulkSuperAdminActionDto,
  ) {
    switch (dto.action) {
      case 'disable':
        await this.updateUserStatus(superAdminIdentifier, targetId, {
          isDisabled: true,
          reason: dto.reason,
        });
        return;
      case 'enable':
        await this.updateUserStatus(superAdminIdentifier, targetId, {
          isDisabled: false,
          reason: dto.reason,
        });
        return;
      default:
        throw new BadRequestException(`Unsupported user action "${dto.action}"`);
    }
  }

  private async performListingBulkAction(
    superAdminIdentifier: string,
    targetId: string,
    dto: BulkSuperAdminActionDto,
  ) {
    const listing = await this.instrumentModel.findById(targetId).select('title imageUrls').lean().exec();
    if (!listing) {
      throw new NotFoundException('Listing not found');
    }

    switch (dto.action) {
      case 'activate':
        await this.instrumentModel.findByIdAndUpdate(targetId, { isActive: true }).exec();
        await this.recordResourceCase({
          actor: superAdminIdentifier,
          caseType: 'marketplace_review',
          resourceType: 'listing',
          resourceId: targetId,
          title: `Listing review: ${(listing as any).title ?? targetId}`,
          description: dto.reason?.trim() ?? '',
          action: 'listing_activated',
          note: dto.reason?.trim() ?? '',
          status: 'resolved',
          priority: dto.priority ?? 'normal',
        });
        return;
      case 'deactivate':
        await this.instrumentModel.findByIdAndUpdate(targetId, { isActive: false }).exec();
        await this.recordResourceCase({
          actor: superAdminIdentifier,
          caseType: 'marketplace_review',
          resourceType: 'listing',
          resourceId: targetId,
          title: `Listing review: ${(listing as any).title ?? targetId}`,
          description: dto.reason?.trim() ?? '',
          action: 'listing_deactivated',
          note: dto.reason?.trim() ?? '',
          status: 'in_review',
          priority: dto.priority ?? 'high',
        });
        return;
      case 'delete':
        await this.instrumentModel.findByIdAndDelete(targetId).exec();
        await Promise.all(((listing as any).imageUrls ?? []).map((url: string) => this.safeDeleteManagedUrl(url)));
        await this.recordResourceCase({
          actor: superAdminIdentifier,
          caseType: 'marketplace_review',
          resourceType: 'listing',
          resourceId: targetId,
          title: `Listing review: ${(listing as any).title ?? targetId}`,
          description: dto.reason?.trim() ?? '',
          action: 'listing_deleted',
          note: dto.reason?.trim() ?? '',
          status: 'resolved',
          priority: 'high',
        });
        return;
      default:
        throw new BadRequestException(`Unsupported listing action "${dto.action}"`);
    }
  }

  private async performRepairShopBulkAction(
    superAdminIdentifier: string,
    targetId: string,
    dto: BulkSuperAdminActionDto,
  ) {
    const shop = await this.repairShopModel.findById(targetId).select('name imageUrls').lean().exec();
    if (!shop) {
      throw new NotFoundException('Repair shop not found');
    }

    switch (dto.action) {
      case 'activate':
        await this.repairShopModel.findByIdAndUpdate(targetId, { isActive: true }).exec();
        await this.recordResourceCase({
          actor: superAdminIdentifier,
          caseType: 'marketplace_review',
          resourceType: 'repair_shop',
          resourceId: targetId,
          title: `Repair shop review: ${(shop as any).name ?? targetId}`,
          description: dto.reason?.trim() ?? '',
          action: 'repair_shop_activated',
          note: dto.reason?.trim() ?? '',
          status: 'resolved',
          priority: dto.priority ?? 'normal',
        });
        return;
      case 'deactivate':
        await this.repairShopModel.findByIdAndUpdate(targetId, { isActive: false }).exec();
        await this.recordResourceCase({
          actor: superAdminIdentifier,
          caseType: 'marketplace_review',
          resourceType: 'repair_shop',
          resourceId: targetId,
          title: `Repair shop review: ${(shop as any).name ?? targetId}`,
          description: dto.reason?.trim() ?? '',
          action: 'repair_shop_deactivated',
          note: dto.reason?.trim() ?? '',
          status: 'in_review',
          priority: dto.priority ?? 'high',
        });
        return;
      case 'delete':
        await this.repairShopModel.findByIdAndDelete(targetId).exec();
        await Promise.all(((shop as any).imageUrls ?? []).map((url: string) => this.safeDeleteManagedUrl(url)));
        await this.recordResourceCase({
          actor: superAdminIdentifier,
          caseType: 'marketplace_review',
          resourceType: 'repair_shop',
          resourceId: targetId,
          title: `Repair shop review: ${(shop as any).name ?? targetId}`,
          description: dto.reason?.trim() ?? '',
          action: 'repair_shop_deleted',
          note: dto.reason?.trim() ?? '',
          status: 'resolved',
          priority: 'high',
        });
        return;
      default:
        throw new BadRequestException(`Unsupported repair shop action "${dto.action}"`);
    }
  }

  private async recordResourceCase(params: {
    actor: string;
    caseType: string;
    resourceType: string;
    resourceId: string;
    title: string;
    description: string;
    action: string;
    note: string;
    status: CaseStatus;
    priority: CasePriority;
    assignedTo?: string;
  }): Promise<void> {
    const existing = await this.superAdminCaseModel
      .findOne({
        resourceType: params.resourceType,
        resourceId: params.resourceId,
        status: { $in: ['open', 'in_review'] },
      })
      .sort({ updatedAt: -1 })
      .exec();

    if (!existing) {
      await this.superAdminCaseModel.create({
        title: params.title,
        description: params.description,
        caseType: params.caseType,
        resourceType: params.resourceType,
        resourceId: params.resourceId,
        status: params.status,
        priority: params.priority,
        assignedTo: params.assignedTo ?? '',
        createdBy: params.actor,
        updatedBy: params.actor,
        resolution: params.note,
        events: [
          {
            action: params.action,
            actor: params.actor,
            note: params.note,
            metadata: {},
            createdAt: new Date(),
          },
        ],
      });
      return;
    }

    existing.status = params.status;
    existing.priority = params.priority;
    existing.updatedBy = params.actor;
    existing.title = params.title;
    existing.description = params.description;
    existing.resolution = params.note;
    if (params.assignedTo) {
      existing.assignedTo = params.assignedTo;
    }
    existing.events.push({
      action: params.action,
      actor: params.actor,
      note: params.note,
      metadata: {},
      createdAt: new Date(),
    });
    await existing.save();
  }

  private buildContentCaseTitle(prefix: string, content: string): string {
    const normalized = content.trim();
    return `${prefix} moderation: ${normalized.slice(0, 72) || 'untitled'}`;
  }

  private async applyBulkCaseMetadata(
    superAdminIdentifier: string,
    resourceType: string,
    resourceId: string,
    dto: BulkSuperAdminActionDto,
  ): Promise<void> {
    if (!dto.assignToMe && !dto.priority) {
      return;
    }

    const current = await this.superAdminCaseModel
      .findOne({
        resourceType,
        resourceId,
        status: { $in: ['open', 'in_review'] },
      })
      .sort({ updatedAt: -1 })
      .exec();

    if (!current) {
      return;
    }

    if (dto.assignToMe) {
      current.assignedTo = superAdminIdentifier;
      if (current.status === 'open') {
        current.status = 'in_review';
      }
    }
    if (dto.priority) {
      current.priority = dto.priority as CasePriority;
    }
    current.updatedBy = superAdminIdentifier;
    current.events.push({
      action: 'bulk_case_metadata_update',
      actor: superAdminIdentifier,
      note: dto.reason?.trim() ?? '',
      metadata: {
        assignedTo: dto.assignToMe ? superAdminIdentifier : undefined,
        priority: dto.priority,
      },
      createdAt: new Date(),
    });
    await current.save();
  }

  private async safeDeleteManagedUrl(fileUrl?: string): Promise<void> {
    try {
      await this.storageService.deleteFile(fileUrl);
    } catch {
      // Best-effort cleanup only.
    }
  }

  private resolveRangeDays(range: string): number {
    switch (range) {
      case '7d':
        return 7;
      case '90d':
        return 90;
      case '30d':
      default:
        return 30;
    }
  }

  private async buildDailySeries(
    model: Model<any>,
    filter: Record<string, unknown>,
    days: number,
  ) {
    const buckets = this.createDateBuckets(days);
    const start = buckets[0];
    const rows = await model
      .aggregate([
        {
          $match: {
            ...filter,
            createdAt: { $gte: start },
          },
        },
        {
          $project: {
            bucket: {
              $dateToString: {
                format: '%Y-%m-%d',
                date: '$createdAt',
              },
            },
          },
        },
        {
          $group: {
            _id: '$bucket',
            count: { $sum: 1 },
          },
        },
        { $sort: { _id: 1 } },
      ])
      .exec();

    const counts = new Map<string, number>(
      rows.map((row: { _id: string; count: number }) => [row._id, row.count]),
    );

    return buckets.map((date) => {
      const isoDate = this.formatDateKey(date);
      return {
        date: isoDate,
        label: new Intl.DateTimeFormat('en-GB', {
          month: 'short',
          day: 'numeric',
        }).format(date),
        count: counts.get(isoDate) ?? 0,
      };
    });
  }

  private async buildUserRoleBreakdown() {
    const rows = await this.userModel
      .aggregate([{ $group: { _id: '$role', value: { $sum: 1 } } }])
      .exec();
    return rows.map((row: { _id: string | null; value: number }) => ({
      label: row._id ?? 'unknown',
      value: row.value,
    }));
  }

  private async buildPostTypeBreakdown() {
    const rows = await this.postModel
      .aggregate([
        { $match: { isDeleted: { $ne: true } } },
        { $group: { _id: '$postType', value: { $sum: 1 } } },
      ])
      .exec();

    return rows.map((row: { _id: string | null; value: number }) => ({
      label: row._id ?? 'unknown',
      value: row.value,
    }));
  }

  private async buildListingCategoryBreakdown() {
    const rows = await this.instrumentModel
      .aggregate([
        {
          $project: {
            category: {
              $ifNull: ['$listingCategory', 'musical_instrument'],
            },
          },
        },
        { $group: { _id: '$category', value: { $sum: 1 } } },
      ])
      .exec();

    return rows.map((row: { _id: string | null; value: number }) => ({
      label: row._id ?? 'unknown',
      value: row.value,
    }));
  }

  private createDateBuckets(days: number): Date[] {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const buckets: Date[] = [];

    for (let index = days - 1; index >= 0; index -= 1) {
      const date = new Date(today);
      date.setDate(today.getDate() - index);
      buckets.push(date);
    }

    return buckets;
  }

  private formatDateKey(date: Date): string {
    return date.toISOString().slice(0, 10);
  }

  private buildDefaultSettings(): Omit<SuperAdminSettings, 'scope'> & { scope: string } {
    const publicBaseUrl = this.configService.get<string>('publicBaseUrl', { infer: true }) ?? '';
    const globalPrefix = this.configService.get<string>('globalPrefix', { infer: true }) ?? 'api/v1';

    return {
      scope: this.defaultSettingsScope,
      siteName: 'Oudelaa SuperAdmin',
      publicBaseUrl,
      dashboardApiBaseUrl: publicBaseUrl ? `${publicBaseUrl}/${globalPrefix}` : '',
      corsOrigins:
        (this.configService.get<string[]>('cors.origins', { infer: true }) as string[] | undefined) ??
        [],
      maintenanceMode: false,
      emailEnabled: this.configService.get<boolean>('email.enabled', { infer: true }) ?? false,
      marketplaceAutoApprove: false,
      contentAutoHideFlagged: false,
      notes: '',
      updatedBy: '',
    };
  }

  private buildMusicalInstrumentFilter() {
    return {
      $or: [
        { listingCategory: 'musical_instrument' },
        { listingCategory: { $exists: false } },
        { listingCategory: null },
      ],
    };
  }
}
