import { getDb } from "../db.ts";
import { eq, inArray } from "drizzle-orm";
import { users, wallets, auditLogs } from "../../drizzle/schema.ts";
import { creditWallet, debitWallet } from "../db.ts";

export interface BulkActionResult {
  success: number;
  failed: number;
  errors: { userId: number; error: string }[];
}

/**
 * Bulk suspend users
 */
export async function bulkSuspendUsers(
  userIds: number[],
  reason: string,
  adminId: number
): Promise<BulkActionResult> {
  const db = await getDb();
  if (!db) return { success: 0, failed: userIds.length, errors: [] };

  const result: BulkActionResult = { success: 0, failed: 0, errors: [] };

  for (const userId of userIds) {
    try {
      await db.update(users).set({ isBanned: true }).where(eq(users.id, userId));

      await db.insert(auditLogs).values({
        actorId: adminId,
        actorRole: "admin",
        action: "bulk_suspend_user",
        category: "user_management",
        details: { userId, reason },
      });

      result.success++;
    } catch (error) {
      result.failed++;
      result.errors.push({
        userId,
        error: error instanceof Error ? error.message : "Unknown error",
      });
    }
  }

  return result;
}

/**
 * Bulk unsuspend users
 */
export async function bulkUnsuspendUsers(
  userIds: number[],
  reason: string,
  adminId: number
): Promise<BulkActionResult> {
  const db = await getDb();
  if (!db) return { success: 0, failed: userIds.length, errors: [] };

  const result: BulkActionResult = { success: 0, failed: 0, errors: [] };

  for (const userId of userIds) {
    try {
      await db.update(users).set({ isBanned: false }).where(eq(users.id, userId));

      await db.insert(auditLogs).values({
        actorId: adminId,
        actorRole: "admin",
        action: "bulk_unsuspend_user",
        category: "user_management",
        details: { userId, reason },
      });

      result.success++;
    } catch (error) {
      result.failed++;
      result.errors.push({
        userId,
        error: error instanceof Error ? error.message : "Unknown error",
      });
    }
  }

  return result;
}

/**
 * Bulk promote users to VIP tier
 */
export async function bulkPromoteToVIP(
  userIds: number[],
  vipTier: "bronze" | "silver" | "gold" | "platinum",
  adminId: number
): Promise<BulkActionResult> {
  const db = await getDb();
  if (!db) return { success: 0, failed: userIds.length, errors: [] };

  const result: BulkActionResult = { success: 0, failed: 0, errors: [] };

  for (const userId of userIds) {
    try {
      // Update user VIP tier (assuming vipTier column exists)
      await db
        .update(users)
        .set({ role: "user" }) // Placeholder - would need actual VIP tier column
        .where(eq(users.id, userId));

      await db.insert(auditLogs).values({
        actorId: adminId,
        actorRole: "admin",
        action: "bulk_promote_vip",
        category: "user_management",
        details: { userId, vipTier },
      });

      result.success++;
    } catch (error) {
      result.failed++;
      result.errors.push({
        userId,
        error: error instanceof Error ? error.message : "Unknown error",
      });
    }
  }

  return result;
}

/**
 * Bulk adjust user balances
 */
export async function bulkAdjustBalance(
  userIds: number[],
  currency: "GC" | "SC",
  amount: number,
  reason: string,
  adminId: number
): Promise<BulkActionResult> {
  const result: BulkActionResult = { success: 0, failed: 0, errors: [] };

  for (const userId of userIds) {
    try {
      if (amount > 0) {
        await creditWallet(
          userId,
          currency,
          amount,
          "admin_adjustment",
          `Bulk adjustment: ${reason}`,
          `bulk_adjust_${Date.now()}`,
          "admin_action"
        );
      } else if (amount < 0) {
        await debitWallet(
          userId,
          currency,
          Math.abs(amount),
          "admin_adjustment",
          `Bulk adjustment: ${reason}`,
          `bulk_adjust_${Date.now()}`,
          "admin_action"
        );
      }

      const db = await getDb();
      if (db) {
        await db.insert(auditLogs).values({
          actorId: adminId,
          actorRole: "admin",
          action: "bulk_adjust_balance",
          category: "financial",
          details: { userId, currency, amount, reason },
        });
      }

      result.success++;
    } catch (error) {
      result.failed++;
      result.errors.push({
        userId,
        error: error instanceof Error ? error.message : "Unknown error",
      });
    }
  }

  return result;
}

/**
 * Bulk reset user passwords (send reset email)
 */
export async function bulkResetPasswords(
  userIds: number[],
  adminId: number
): Promise<BulkActionResult> {
  const db = await getDb();
  if (!db) return { success: 0, failed: userIds.length, errors: [] };

  const result: BulkActionResult = { success: 0, failed: 0, errors: [] };

  for (const userId of userIds) {
    try {
      // In a real implementation, this would generate reset tokens and send emails
      await db.insert(auditLogs).values({
        actorId: adminId,
        actorRole: "admin",
        action: "bulk_reset_password",
        category: "user_management",
        details: { userId },
      });

      result.success++;
    } catch (error) {
      result.failed++;
      result.errors.push({
        userId,
        error: error instanceof Error ? error.message : "Unknown error",
      });
    }
  }

  return result;
}

/**
 * Bulk clear user session (force logout)
 */
export async function bulkClearSessions(
  userIds: number[],
  adminId: number
): Promise<BulkActionResult> {
  const db = await getDb();
  if (!db) return { success: 0, failed: userIds.length, errors: [] };

  const result: BulkActionResult = { success: 0, failed: 0, errors: [] };

  for (const userId of userIds) {
    try {
      // In a real implementation, this would invalidate all sessions for the user
      await db.insert(auditLogs).values({
        actorId: adminId,
        actorRole: "admin",
        action: "bulk_clear_sessions",
        category: "security",
        details: { userId },
      });

      result.success++;
    } catch (error) {
      result.failed++;
      result.errors.push({
        userId,
        error: error instanceof Error ? error.message : "Unknown error",
      });
    }
  }

  return result;
}
