import { db } from "./db";
import { teams, players, coaches, teamCoaches, users } from "@shared/schema";
import { eq } from "drizzle-orm";
import { scrypt, randomBytes } from "crypto";
import { promisify } from "util";

const scryptAsync = promisify(scrypt);

async function hashPassword(password: string): Promise<string> {
  const salt = randomBytes(16).toString("hex");
  const buf = (await scryptAsync(password, salt, 64)) as Buffer;
  return `${buf.toString("hex")}.${salt}`;
}

export async function createSampleData() {
  try {
    console.log("Creating sample data...");
    
    // Check if data already exists
    const existingTeams = await db.select().from(teams);
    console.log("Existing teams count:", existingTeams.length);
    
    if (existingTeams.length > 0) {
      console.log("Sample data already exists, clearing and recreating...");
      // Clear existing data for fresh start
      await db.delete(teamCoaches);
      await db.delete(players);
      await db.delete(coaches);
      await db.delete(teams);
    }

    // Create sample teams using simple inserts
    const team1Data = {
      name: "Thunder Hawks",
      sport: "basketball",
      status: "active" as const,
      description: "Elite basketball team with championship aspirations",
    };

    const team2Data = {
      name: "Lightning Bolts", 
      sport: "soccer",
      status: "active" as const,
      description: "Dynamic soccer team known for fast-paced gameplay",
    };

    const team3Data = {
      name: "Storm Eagles",
      sport: "football", 
      status: "active" as const,
      description: "Professional football team with strong defensive strategies",
    };

    const team4Data = {
      name: "Fire Dragons",
      sport: "hockey",
      status: "active" as const, 
      description: "Aggressive hockey team with excellent offensive capabilities",
    };

    const [team1] = await db.insert(teams).values(team1Data).returning();
    const [team2] = await db.insert(teams).values(team2Data).returning();
    const [team3] = await db.insert(teams).values(team3Data).returning();
    const [team4] = await db.insert(teams).values(team4Data).returning();

    console.log("Teams created:", { team1: team1.id, team2: team2.id, team3: team3.id, team4: team4.id });

    // Create sample coaches
    const coachesData = [
      {
        firstName: "Michael",
        lastName: "Johnson", 
        email: "michael.johnson@sportspro.com",
        phone: "+1-555-0101",
        experience: 15,
        specialization: "head_coach" as const,
        status: "active" as const,
      },
      {
        firstName: "Sarah",
        lastName: "Williams",
        email: "sarah.williams@sportspro.com",
        phone: "+1-555-0102", 
        experience: 8,
        specialization: "assistant_coach" as const,
        status: "active" as const,
      },
      {
        firstName: "David",
        lastName: "Brown",
        email: "david.brown@sportspro.com",
        phone: "+1-555-0103",
        experience: 12,
        specialization: "strength_conditioning" as const,
        status: "active" as const,
      },
      {
        firstName: "Lisa",
        lastName: "Garcia",
        email: "lisa.garcia@sportspro.com",
        phone: "+1-555-0104",
        experience: 6, 
        specialization: "defensive_coordinator" as const,
        status: "active" as const,
      }
    ];

    const createdCoaches = await db.insert(coaches).values(coachesData).returning();
    console.log("Coaches created:", createdCoaches.length);

    // Create sample players
    const playersData = [
      {
        firstName: "James",
        lastName: "Anderson",
        email: "james.anderson@email.com",
        phone: "+1-555-1001", 
        dateOfBirth: "2000-03-15",
        gender: "male" as const,
        position: "Point Guard",
        jerseyNumber: 23,
        height: 185,
        weight: 80,
        status: "active" as const,
        teamId: team1.id,
        emergencyContact: "Mary Anderson - +1-555-2001",
      },
      {
        firstName: "Marcus", 
        lastName: "Johnson",
        email: "marcus.johnson@email.com",
        phone: "+1-555-1002",
        dateOfBirth: "1999-07-22",
        gender: "male" as const,
        position: "Shooting Guard",
        jerseyNumber: 15,
        height: 190,
        weight: 85,
        status: "active" as const,
        teamId: team1.id,
        emergencyContact: "Linda Johnson - +1-555-2002",
      },
      {
        firstName: "Sophia",
        lastName: "Davis", 
        email: "sophia.davis@email.com",
        phone: "+1-555-1003",
        dateOfBirth: "2001-01-10",
        gender: "female" as const,
        position: "Center",
        jerseyNumber: 32,
        height: 195,
        weight: 90,
        status: "active" as const,
        teamId: team1.id,
        emergencyContact: "Robert Davis - +1-555-2003",
      },
      {
        firstName: "Carlos",
        lastName: "Rodriguez",
        email: "carlos.rodriguez@email.com",
        phone: "+1-555-1004",
        dateOfBirth: "1998-11-05",
        gender: "male" as const,
        position: "Midfielder",
        jerseyNumber: 10,
        height: 175,
        weight: 70,
        status: "active" as const,
        teamId: team2.id,
        emergencyContact: "Maria Rodriguez - +1-555-2004",
      },
      {
        firstName: "Emma",
        lastName: "Wilson",
        email: "emma.wilson@email.com", 
        phone: "+1-555-1005",
        dateOfBirth: "2000-09-18",
        gender: "female" as const,
        position: "Forward",
        jerseyNumber: 9,
        height: 168,
        weight: 65,
        status: "active" as const,
        teamId: team2.id,
        emergencyContact: "Tom Wilson - +1-555-2005",
      },
      {
        firstName: "Diego",
        lastName: "Martinez",
        email: "diego.martinez@email.com",
        phone: "+1-555-1006",
        dateOfBirth: "1999-12-03",
        gender: "male" as const,
        position: "Goalkeeper",
        jerseyNumber: 1,
        height: 182,
        weight: 78,
        status: "active" as const,
        teamId: team2.id,
        emergencyContact: "Ana Martinez - +1-555-2006",
      },
      {
        firstName: "Tyler",
        lastName: "Thompson",
        email: "tyler.thompson@email.com",
        phone: "+1-555-1007",
        dateOfBirth: "1997-05-14",
        gender: "male" as const,
        position: "Quarterback",
        jerseyNumber: 12,
        height: 188,
        weight: 95,
        status: "active" as const,
        teamId: team3.id,
        emergencyContact: "Susan Thompson - +1-555-2007",
      },
      {
        firstName: "Ashley",
        lastName: "Lee", 
        email: "ashley.lee@email.com",
        phone: "+1-555-1008",
        dateOfBirth: "2000-08-27",
        gender: "female" as const,
        position: "Wide Receiver",
        jerseyNumber: 88,
        height: 172,
        weight: 68,
        status: "active" as const,
        teamId: team3.id,
        emergencyContact: "Michael Lee - +1-555-2008",
      },
      {
        firstName: "Connor",
        lastName: "O'Brien",
        email: "connor.obrien@email.com",
        phone: "+1-555-1009",
        dateOfBirth: "1999-02-11",
        gender: "male" as const,
        position: "Center",
        jerseyNumber: 19,
        height: 185,
        weight: 88,
        status: "active" as const,
        teamId: team4.id,
        emergencyContact: "Patricia O'Brien - +1-555-2009",
      },
      {
        firstName: "Madison",
        lastName: "Taylor",
        email: "madison.taylor@email.com", 
        phone: "+1-555-1010",
        dateOfBirth: "2001-06-30",
        gender: "female" as const,
        position: "Left Wing",
        jerseyNumber: 17,
        height: 170,
        weight: 65,
        status: "active" as const,
        teamId: team4.id,
        emergencyContact: "John Taylor - +1-555-2010",
      },
    ];

    const createdPlayers = await db.insert(players).values(playersData).returning();
    console.log("Players created:", createdPlayers.length);

    // Assign coaches to teams (allowing multiple assignments)
    const teamCoachAssignments = [
      {
        teamId: team1.id,
        coachId: createdCoaches[0].id,
        role: "head_coach" as const,
        startDate: "2024-01-01",
      },
      {
        teamId: team2.id,
        coachId: createdCoaches[1].id,
        role: "head_coach" as const,
        startDate: "2024-01-01",
      },
      {
        teamId: team3.id,
        coachId: createdCoaches[2].id,
        role: "head_coach" as const,
        startDate: "2024-01-01",
      },
      {
        teamId: team4.id,
        coachId: createdCoaches[3].id,
        role: "head_coach" as const,
        startDate: "2024-01-01",
      },
      // Example of coach working with multiple teams
      {
        teamId: team1.id,
        coachId: createdCoaches[2].id,
        role: "assistant_coach" as const,
        startDate: "2024-01-01",
      },
    ];

    await db.insert(teamCoaches).values(teamCoachAssignments);
    console.log("Team-coach assignments created");

    // Create coaching feedback reactions
    const feedbackReactions = [
      // Positive reactions
      {
        name: "Great Job",
        emoji: "👏",
        category: "positive",
        color: "#10B981",
        isActive: true,
        sortOrder: 1,
      },
      {
        name: "Excellent",
        emoji: "⭐",
        category: "positive", 
        color: "#059669",
        isActive: true,
        sortOrder: 2,
      },
      {
        name: "Keep It Up",
        emoji: "🔥",
        category: "positive",
        color: "#047857",
        isActive: true,
        sortOrder: 3,
      },
      {
        name: "Perfect Form",
        emoji: "💪",
        category: "positive",
        color: "#065F46",
        isActive: true,
        sortOrder: 4,
      },
      // Negative/Corrective reactions
      {
        name: "Focus",
        emoji: "👀",
        category: "negative",
        color: "#EF4444",
        isActive: true,
        sortOrder: 5,
      },
      {
        name: "Try Again",
        emoji: "🔄",
        category: "negative",
        color: "#DC2626",
        isActive: true,
        sortOrder: 6,
      },
      {
        name: "Slow Down",
        emoji: "⚠️",
        category: "negative",
        color: "#B91C1C",
        isActive: true,
        sortOrder: 7,
      },
      {
        name: "Wrong Technique",
        emoji: "❌",
        category: "negative",
        color: "#991B1B",
        isActive: true,
        sortOrder: 8,
      },
      // Instructional reactions
      {
        name: "Listen Up",
        emoji: "👂",
        category: "instruction",
        color: "#F59E0B",
        isActive: true,
        sortOrder: 9,
      },
      {
        name: "Time Out",
        emoji: "⏰",
        category: "instruction",
        color: "#D97706",
        isActive: true,
        sortOrder: 10,
      },
      {
        name: "Come Here",
        emoji: "👋",
        category: "instruction",
        color: "#B45309",
        isActive: true,
        sortOrder: 11,
      },
      {
        name: "Water Break",
        emoji: "💧",
        category: "instruction",
        color: "#92400E",
        isActive: true,
        sortOrder: 12,
      },
      // Neutral reactions
      {
        name: "Good Effort",
        emoji: "👍",
        category: "neutral",
        color: "#6B7280",
        isActive: true,
        sortOrder: 13,
      },
      {
        name: "Almost There",
        emoji: "🎯",
        category: "neutral",
        color: "#4B5563",
        isActive: true,
        sortOrder: 14,
      },
      {
        name: "Keep Trying",
        emoji: "💪",
        category: "neutral",
        color: "#374151",
        isActive: true,
        sortOrder: 15,
      },
      {
        name: "Next Time",
        emoji: "⏭️",
        category: "neutral",
        color: "#1F2937",
        isActive: true,
        sortOrder: 16,
      },
    ];

    await db.insert(coachingFeedbackReactions).values(feedbackReactions);
    console.log("Coaching feedback reactions created");

    // Create demo user for easy login
    const demoPassword = await hashPassword("demo123");
    const demoUser = {
      id: "demo-user-001",
      firstName: "Demo",
      lastName: "User", 
      email: "demo@rugby.com",
      password: demoPassword,
      role: "org_admin",
      createdAt: new Date(),
      updatedAt: new Date()
    };

    // Create super admin user
    const superAdminPassword = await hashPassword("superadmin123");
    const superAdminUser = {
      id: "super-admin-001",
      firstName: "Super",
      lastName: "Admin",
      email: "admin@sportspro.com",
      password: superAdminPassword,
      role: "super_admin",
      createdAt: new Date(),
      updatedAt: new Date()
    };

    // Check if demo user already exists
    const existingDemoUser = await db.select().from(users).where(eq(users.email, "demo@rugby.com"));
    if (existingDemoUser.length === 0) {
      await db.insert(users).values(demoUser);
      console.log("Demo user created - Email: demo@rugby.com, Password: demo123");
    } else {
      console.log("Demo user already exists");
    }

    // Check if super admin user already exists
    const existingSuperAdmin = await db.select().from(users).where(eq(users.email, "admin@sportspro.com"));
    if (existingSuperAdmin.length === 0) {
      await db.insert(users).values(superAdminUser);
      console.log("Super Admin user created - Email: admin@sportspro.com, Password: superadmin123");
    } else {
      console.log("Super Admin user already exists");
    }

    console.log("Sample data created successfully!");

  } catch (error) {
    console.error("Error creating sample data:", error);
    throw error;
  }
}