#!/usr/bin/env node
// scripts/seed-socket-test-data.ts
// Copyright (C) 2026 Robert Colbert <rob.colbert@openplatform.us>
// All Rights Reserved

/**
 * Seeds the database with test data for socket messaging tests.
 *
 * This script creates:
 * - Test user (if not exists)
 * - Test project (unique per run)
 * - Test chat session (unique per run)
 * - Test drone registrations (unique per run)
 *
 * IMPORTANT: This script does NOT delete existing data. It only creates new,
 * unique records. Tests are responsible for cleaning up their own data.
 *
 * Usage:
 *   npx tsx scripts/seed-socket-test-data.ts
 *
 * Output:
 *   JSON object with created resource IDs for test cleanup
 */

import mongoose from "mongoose";
import { config } from "dotenv";
import { IUser } from "@gadget/api";
import User from "../src/models/user";
import Project from "../src/models/project";
import ChatSession from "../src/models/chat-session";
import DroneRegistration from "../src/models/drone-registration";
import { AiProvider } from "../src/models/ai-provider";

config();

interface SeedResult {
  userId: string;
  projectId: string;
  chatSessionId: string;
  droneIds: string[];
  providerId?: string;
  createdAt: string;
  note: string;
}

async function seedSocketTestData(): Promise<SeedResult> {
  const NOW = new Date();
  const timestamp = NOW.toISOString().replace(/[:.]/g, "-");

  try {
    // Connect to database
    await mongoose.connect(
      process.env.MONGODB_URI || "mongodb://localhost:27017/gadget-code",
    );
    console.log("Connected to MongoDB");

    // Find or create test user
    let user = await User.findOne({ email: "test-socket@gadget-code.test" });
    if (!user) {
      user = new User({
        email: "test-socket@gadget-code.test",
        displayName: "Socket Test User",
        passwordSalt: "test-salt",
        passwordHash: "test-hash",
        banned: false,
        admin: false,
        createdAt: NOW,
        updatedAt: NOW,
      });
      await user.save();
      console.log("Created test user:", user._id);
    } else {
      console.log("Found existing test user:", user._id);
    }

    // Find or create a test AI provider
    let provider = await AiProvider.findOne({ name: "Test Socket Provider" });
    if (!provider) {
      provider = new AiProvider({
        name: "Test Socket Provider",
        apiType: "ollama",
        baseUrl: "http://localhost:11434",
        enabled: true,
        models: [
          {
            id: "llama3.2",
            name: "Llama 3.2",
            capabilities: {
              canCallTools: true,
              hasVision: false,
              hasEmbedding: false,
              hasThinking: false,
              isInstructTuned: true,
            },
          },
        ],
        lastModelRefresh: NOW,
      });
      await provider.save();
      console.log("Created test provider:", provider._id);
    } else {
      console.log("Found existing test provider:", provider._id);
    }

    // Create test project (unique per run)
    const project = new Project({
      user: user._id,
      slug: `socket-test-${timestamp}`,
      name: `Socket Test Project ${timestamp}`,
      gitUrl: "https://github.com/test/socket-test.git",
      createdAt: NOW,
      updatedAt: NOW,
    });
    await project.save();
    console.log("Created test project:", project._id);

    // Create test chat session (unique per run)
    const chatSession = new ChatSession({
      user: user._id,
      project: project._id,
      provider: provider._id,
      selectedModel: "llama3.2",
      mode: "build",
      name: `Socket Test Session ${timestamp}`,
      stats: {
        toolCallCount: 0,
        fileOpCount: 0,
        subagentCount: 0,
      },
      createdAt: NOW,
      updatedAt: NOW,
    });
    await chatSession.save();
    console.log("Created test chat session:", chatSession._id);

    // Create test drone registrations (unique per run)
    const droneCount = 3;
    const droneIds: string[] = [];

    for (let i = 0; i < droneCount; i++) {
      const drone = new DroneRegistration({
        user: user._id,
        hostname: `test-drone-${timestamp}-${i}`,
        workspaceDir: `/tmp/socket-test-${timestamp}-${i}`,
        status: "available",
        createdAt: NOW,
        updatedAt: NOW,
      });
      await drone.save();
      droneIds.push(drone._id);
      console.log(`Created test drone ${i + 1}/${droneCount}:`, drone._id);
    }

    const result: SeedResult = {
      userId: user._id,
      projectId: project._id,
      chatSessionId: chatSession._id,
      droneIds,
      providerId: provider._id,
      createdAt: NOW.toISOString(),
      note: "TEST DATA - Safe to delete. Created for socket messaging tests.",
    };

    console.log("\n✅ Seed complete! Save this output for test cleanup:");
    console.log(JSON.stringify(result, null, 2));

    return result;
  } catch (error) {
    console.error("❌ Seed failed:", error);
    process.exit(1);
  } finally {
    await mongoose.disconnect();
    console.log("\nDisconnected from MongoDB");
  }
}

// Run the seed
seedSocketTestData()
  .then(() => {
    process.exit(0);
  })
  .catch((error) => {
    console.error("Unhandled error:", error);
    process.exit(1);
  });
