import type { Express } from "express";
import express from "express";
import { createServer, type Server } from "http";
import { storage } from "./storage";
import { setupLocalAuth, requireAuth, hashPassword } from "./local-auth";
import {
  insertTeamSchema,
  insertPlayerSchema,
  insertCoachSchema,
  insertTeamCoachSchema,
  insertMembershipFeeSchema,
  insertPaymentActivitySchema,
  insertPaymentNotificationSchema,
  insertAutomaticPaymentScheduleSchema,
  insertMemberStatusHistorySchema,
  insertSubscriptionPlanSchema,

  insertTournamentSchema,
  insertMatchSchema,
  insertLeagueSchema,
  insertLeagueTeamSchema,
  insertVenueSchema,
  insertRefereeSchema,
  insertFixtureSchema,
  insertMatchEventSchema,
  insertMatchStatisticsSchema,
  insertPlayerTransferSchema,
} from "@shared/schema";
import { z } from "zod";
import multer from "multer";
import path from "path";
import fs from "fs";
import { sendWelcomeEmail } from "./email";
import { generatePassword, generateUsername, validatePassword } from "./password";
import { sendVerificationEmail, verifyEmail } from "./verification";
import { 
  videoUpload, 
  uploadVideo, 
  analyzeVideo, 
  getAnalysisStatus, 
  generateHighlights, 
  getVideoLibrary, 
  deleteVideo 
} from "./video-highlights";
import { registerThemeRoutes } from "./theme-routes";
import { getSmartOnboardingData } from "./smart-onboarding-engine";
import { registerCmsRoutes } from "./cms-routes";
import { reportsService } from "./reports-service";
import { isInstalled, runInstallation, testDatabaseConnection, getInstallationStatus } from "./installation";

// Create uploads directory if it doesn't exist
const uploadsDir = path.join(process.cwd(), "uploads");
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { recursive: true });
}

// Configure multer for file uploads
const upload = multer({
  dest: uploadsDir,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB limit
  },
  fileFilter: (req, file, cb) => {
    // Allow images and common file types
    const allowedTypes = [
      "image/jpeg",
      "image/png",
      "image/gif",
      "image/webp",
      "application/pdf",
      "text/csv",
      "application/vnd.ms-excel",
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    ];
    
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error("Invalid file type"));
    }
  },
});

// Super Admin middleware
function requireSuperAdmin(req: any, res: any, next: any) {
  if (!req.user) {
    return res.status(401).json({ message: "Not authenticated" });
  }
  
  if (req.user.role !== 'superadmin') {
    return res.status(403).json({ message: "Super admin access required" });
  }
  
  next();
}

export async function registerRoutes(app: Express): Promise<Server> {
  // Installation routes (no auth required, but only accessible during installation)
  app.get("/api/installation/status", (req, res) => {
    res.json(getInstallationStatus());
  });

  // Middleware to check if installation is already complete
  const requireNotInstalled = (req: any, res: any, next: any) => {
    const status = getInstallationStatus();
    if (status.installed) {
      return res.status(403).json({ message: "Application is already installed" });
    }
    next();
  };

  app.post("/api/installation/test-db", requireNotInstalled, async (req, res) => {
    const result = await testDatabaseConnection(req.body.databaseUrl);
    res.json(result);
  });

  app.post("/api/installation/install", requireNotInstalled, async (req, res) => {
    const result = await runInstallation(req.body);
    res.json(result);
  });

  // Setup authentication
  setupLocalAuth(app);

  // Serve uploaded files
  app.use("/uploads", express.static(uploadsDir));

  // Health check
  app.get("/api/health", (req, res) => {
    res.json({ status: "ok", timestamp: new Date().toISOString() });
  });

  // Admin user management routes
  app.get("/api/admin/users", requireAuth, async (req, res) => {
    try {
      const users = await storage.getAllUsers();
      res.json(users);
    } catch (error) {
      console.error("Error fetching users:", error);
      res.status(500).json({ message: "Failed to fetch users" });
    }
  });

  app.post("/api/admin/users", requireAuth, async (req, res) => {
    try {
      const { firstName, lastName, email, role, password } = req.body;
      
      // Generate username and validate password
      const username = generateUsername(firstName, lastName);
      const validationResult = validatePassword(password);
      
      if (!validationResult.isValid) {
        return res.status(400).json({ 
          message: "Password validation failed", 
          errors: validationResult.errors 
        });
      }

      // Hash the password
      const hashedPassword = await hashPassword(password);

      // Create the user
      const userData = {
        id: crypto.randomUUID(),
        firstName,
        lastName,
        email,
        username,
        password: hashedPassword,
        role,
        authType: "local" as const,
        isActive: true,
        status: "active" as const,
      };

      const user = await storage.createUser(userData);

      // Send welcome email (optional, only if email service is configured)
      // SECURITY: Never send passwords in emails - users should use password reset if needed
      try {
        await sendWelcomeEmail({
          to: email,
          firstName,
          lastName,
          username,
          password: "Please use the password reset link to set your password", // Never send actual password
        });
      } catch (emailError) {
        console.warn("Failed to send welcome email:", emailError);
        // Continue execution - email failure shouldn't block user creation
      }

      res.json({ 
        user: { ...user, password: undefined }, // Don't return password
        message: "User created successfully"
      });
    } catch (error) {
      console.error("Error creating user:", error);
      res.status(500).json({ message: "Failed to create user" });
    }
  });

  // Subscription and Membership Fee Management Routes
  
  // Membership fees
  app.get("/api/membership-fees", requireAuth, async (req, res) => {
    try {
      const organizationId = req.query.organizationId ? parseInt(req.query.organizationId as string) : undefined;
      const fees = await storage.getMembershipFees(organizationId);
      res.json(fees);
    } catch (error) {
      console.error("Error fetching membership fees:", error);
      res.status(500).json({ message: "Failed to fetch membership fees" });
    }
  });

  app.post("/api/membership-fees", requireAuth, async (req, res) => {
    try {
      const feeData = insertMembershipFeeSchema.parse(req.body);
      const fee = await storage.createMembershipFee(feeData);
      
      // Schedule automatic payment reminder
      const reminderDate = new Date(fee.dueDate);
      reminderDate.setDate(reminderDate.getDate() - 3); // 3 days before due date
      
      if (reminderDate > new Date()) {
        await storage.schedulePaymentReminder(fee.id, reminderDate);
      }
      
      res.json(fee);
    } catch (error) {
      console.error("Error creating membership fee:", error);
      res.status(500).json({ message: "Failed to create membership fee" });
    }
  });

  app.get("/api/membership-fees/overdue", requireAuth, async (req, res) => {
    try {
      const overdueFees = await storage.getOverdueFees();
      res.json(overdueFees);
    } catch (error) {
      console.error("Error fetching overdue fees:", error);
      res.status(500).json({ message: "Failed to fetch overdue fees" });
    }
  });

  app.get("/api/membership-fees/user/:userId", requireAuth, async (req, res) => {
    try {
      const userId = req.params.userId;
      const fees = await storage.getUserMembershipFees(userId);
      res.json(fees);
    } catch (error) {
      console.error("Error fetching user membership fees:", error);
      res.status(500).json({ message: "Failed to fetch user membership fees" });
    }
  });

  app.put("/api/membership-fees/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const feeData = req.body;
      const fee = await storage.updateMembershipFee(id, feeData);
      res.json(fee);
    } catch (error) {
      console.error("Error updating membership fee:", error);
      res.status(500).json({ message: "Failed to update membership fee" });
    }
  });

  // Payment activities
  app.get("/api/payment-activities", requireAuth, async (req, res) => {
    try {
      const membershipFeeId = req.query.membershipFeeId ? parseInt(req.query.membershipFeeId as string) : undefined;
      const activities = await storage.getPaymentActivities(membershipFeeId);
      res.json(activities);
    } catch (error) {
      console.error("Error fetching payment activities:", error);
      res.status(500).json({ message: "Failed to fetch payment activities" });
    }
  });

  app.post("/api/payment-activities", requireAuth, async (req, res) => {
    try {
      const activityData = insertPaymentActivitySchema.parse(req.body);
      const activity = await storage.createPaymentActivity(activityData);
      
      // If payment is completed, update membership fee status and reactivate member if suspended
      if (activity.status === 'completed') {
        await storage.updateMembershipFee(activity.membershipFeeId, { status: 'paid' });
        
        if (activity.userId) {
          const user = await storage.getUser(activity.userId);
          if (user && user.status === 'suspended') {
            await storage.reactivateMember(activity.userId, activity.organizationId);
          }
        }
      }
      
      res.json(activity);
    } catch (error) {
      console.error("Error creating payment activity:", error);
      res.status(500).json({ message: "Failed to create payment activity" });
    }
  });

  app.get("/api/payment-activities/user/:userId", requireAuth, async (req, res) => {
    try {
      const userId = req.params.userId;
      const activities = await storage.getPaymentHistory(userId);
      res.json(activities);
    } catch (error) {
      console.error("Error fetching payment history:", error);
      res.status(500).json({ message: "Failed to fetch payment history" });
    }
  });

  app.put("/api/payment-activities/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const activityData = req.body;
      const activity = await storage.updatePaymentActivity(id, activityData);
      res.json(activity);
    } catch (error) {
      console.error("Error updating payment activity:", error);
      res.status(500).json({ message: "Failed to update payment activity" });
    }
  });

  // Payment notifications
  app.get("/api/payment-notifications/pending", requireAuth, async (req, res) => {
    try {
      const notifications = await storage.getPendingNotifications();
      res.json(notifications);
    } catch (error) {
      console.error("Error fetching pending notifications:", error);
      res.status(500).json({ message: "Failed to fetch pending notifications" });
    }
  });

  app.post("/api/payment-notifications", requireAuth, async (req, res) => {
    try {
      const notificationData = insertPaymentNotificationSchema.parse(req.body);
      const notification = await storage.createPaymentNotification(notificationData);
      res.json(notification);
    } catch (error) {
      console.error("Error creating payment notification:", error);
      res.status(500).json({ message: "Failed to create payment notification" });
    }
  });

  app.put("/api/payment-notifications/:id/status", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const { status } = req.body;
      await storage.updateNotificationStatus(id, status);
      res.json({ message: "Notification status updated" });
    } catch (error) {
      console.error("Error updating notification status:", error);
      res.status(500).json({ message: "Failed to update notification status" });
    }
  });

  // Automatic payment schedules
  app.get("/api/automatic-payment-schedules", requireAuth, async (req, res) => {
    try {
      const schedules = await storage.getActivePaymentSchedules();
      res.json(schedules);
    } catch (error) {
      console.error("Error fetching payment schedules:", error);
      res.status(500).json({ message: "Failed to fetch payment schedules" });
    }
  });

  app.post("/api/automatic-payment-schedules", requireAuth, async (req, res) => {
    try {
      const scheduleData = insertAutomaticPaymentScheduleSchema.parse(req.body);
      const schedule = await storage.createAutomaticPaymentSchedule(scheduleData);
      res.json(schedule);
    } catch (error) {
      console.error("Error creating payment schedule:", error);
      res.status(500).json({ message: "Failed to create payment schedule" });
    }
  });

  app.put("/api/automatic-payment-schedules/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const scheduleData = req.body;
      const schedule = await storage.updatePaymentSchedule(id, scheduleData);
      res.json(schedule);
    } catch (error) {
      console.error("Error updating payment schedule:", error);
      res.status(500).json({ message: "Failed to update payment schedule" });
    }
  });

  app.delete("/api/automatic-payment-schedules/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.suspendPaymentSchedule(id);
      res.json({ message: "Payment schedule suspended" });
    } catch (error) {
      console.error("Error suspending payment schedule:", error);
      res.status(500).json({ message: "Failed to suspend payment schedule" });
    }
  });

  // Member status management
  app.get("/api/member-status/:userId", requireAuth, async (req, res) => {
    try {
      const userId = req.params.userId;
      const history = await storage.getMemberStatusHistory(userId);
      res.json(history);
    } catch (error) {
      console.error("Error fetching member status history:", error);
      res.status(500).json({ message: "Failed to fetch member status history" });
    }
  });

  app.post("/api/member-status/suspend", requireAuth, async (req, res) => {
    try {
      const { userId, organizationId, membershipFeeId } = req.body;
      await storage.suspendMemberForNonPayment(userId, organizationId, membershipFeeId);
      res.json({ message: "Member suspended for non-payment" });
    } catch (error) {
      console.error("Error suspending member:", error);
      res.status(500).json({ message: "Failed to suspend member" });
    }
  });

  app.post("/api/member-status/reactivate", requireAuth, async (req, res) => {
    try {
      const { userId, organizationId } = req.body;
      await storage.reactivateMember(userId, organizationId);
      res.json({ message: "Member reactivated" });
    } catch (error) {
      console.error("Error reactivating member:", error);
      res.status(500).json({ message: "Failed to reactivate member" });
    }
  });

  // Process overdue payments and automatic suspensions
  app.post("/api/process-overdue-payments", requireAuth, async (req, res) => {
    try {
      const overdueFees = await storage.getOverdueFees();
      let processedCount = 0;
      
      for (const fee of overdueFees) {
        const gracePeriodEnd = new Date(fee.dueDate);
        gracePeriodEnd.setDate(gracePeriodEnd.getDate() + (fee.gracePeriodDays || 7));
        
        if (new Date() > gracePeriodEnd && fee.userId) {
          // Update fee status to overdue
          await storage.updateMembershipFee(fee.id, { status: 'overdue' });
          
          // Suspend member
          await storage.suspendMemberForNonPayment(fee.userId, fee.organizationId, fee.id);
          
          // Send final notice notification
          await storage.createPaymentNotification({
            membershipFeeId: fee.id,
            userId: fee.userId,
            organizationId: fee.organizationId,
            notificationType: 'final_notice',
            method: 'email',
            scheduledFor: new Date(),
            subject: 'Final Payment Notice - Account Suspended',
            message: `Your account has been suspended due to overdue payment of $${(fee.amount / 100).toFixed(2)}. Please contact us to resolve this issue.`,
            emailAddress: '',
          });
          
          processedCount++;
        }
      }
      
      res.json({ message: `Processed ${processedCount} overdue payments` });
    } catch (error) {
      console.error("Error processing overdue payments:", error);
      res.status(500).json({ message: "Failed to process overdue payments" });
    }
  });

  // Team routes
  app.get("/api/teams", requireAuth, async (req, res) => {
    try {
      const teams = await storage.getTeams();
      res.json(teams);
    } catch (error) {
      console.error("Error fetching teams:", error);
      res.status(500).json({ message: "Failed to fetch teams" });
    }
  });

  app.get("/api/teams/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const team = await storage.getTeam(id);
      if (!team) {
        return res.status(404).json({ message: "Team not found" });
      }
      res.json(team);
    } catch (error) {
      console.error("Error fetching team:", error);
      res.status(500).json({ message: "Failed to fetch team" });
    }
  });

  app.get("/api/teams/:id/details", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const team = await storage.getTeam(id);
      if (!team) {
        return res.status(404).json({ message: "Team not found" });
      }

      // Get additional details like coaches
      const coaches = await storage.getTeamCoaches(id);
      
      const teamDetails = {
        ...team,
        coaches: coaches || []
      };

      res.json(teamDetails);
    } catch (error) {
      console.error("Error fetching team details:", error);
      res.status(500).json({ message: "Failed to fetch team details" });
    }
  });

  app.get("/api/teams/:id/player-stats", requireAuth, async (req, res) => {
    try {
      const teamId = parseInt(req.params.id);
      if (isNaN(teamId)) {
        return res.status(400).json({ message: "Invalid team ID" });
      }
      
      const players = await storage.getPlayersByTeam(teamId);
      
      // Calculate statistics
      const genderStats: Record<string, number> = players.reduce((acc, player) => {
        const gender = player.gender || 'Unknown';
        acc[gender] = (acc[gender] || 0) + 1;
        return acc;
      }, {} as Record<string, number>);

      const statusStats: Record<string, number> = players.reduce((acc, player) => {
        const status = player.status || 'Unknown';
        acc[status] = (acc[status] || 0) + 1;
        return acc;
      }, {} as Record<string, number>);

      const stats = {
        total: players.length,
        byGender: genderStats,
        byStatus: statusStats,
        coachCount: 0, // Will be updated with actual coach data
        players: players
      };

      res.json(stats);
    } catch (error) {
      console.error("Error fetching team player stats:", error);
      res.status(500).json({ message: "Failed to fetch team player stats" });
    }
  });

  app.post("/api/teams", requireAuth, upload.single("logo"), async (req, res) => {
    try {
      // Convert organizationId from string to number if present
      const processedBody = { ...req.body };
      if (processedBody.organizationId) {
        processedBody.organizationId = parseInt(processedBody.organizationId);
      }
      
      const teamData = insertTeamSchema.parse(processedBody);
      if (req.file) {
        teamData.logoUrl = `/uploads/${req.file.filename}`;
      }
      const team = await storage.createTeam(teamData);
      res.json(team);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ message: "Invalid team data", errors: error.errors });
      }
      console.error("Error creating team:", error);
      res.status(500).json({ message: "Failed to create team" });
    }
  });

  app.put("/api/teams/:id", requireAuth, async (req, res, next) => {
    // Check if request has multipart/form-data (file upload)
    const contentType = req.get('content-type') || '';
    if (contentType.includes('multipart/form-data')) {
      // Use multer for file uploads
      upload.single("logo")(req, res, async (err) => {
        if (err) {
          return res.status(400).json({ message: "File upload error" });
        }
        try {
          const id = parseInt(req.params.id);
          const teamData = req.body;
          if (req.file) {
            teamData.logoUrl = `/uploads/${req.file.filename}`;
          }
          const team = await storage.updateTeam(id, teamData);
          res.json(team);
        } catch (error) {
          console.error("Error updating team:", error);
          res.status(500).json({ message: "Failed to update team" });
        }
      });
    } else {
      // Handle JSON request
      try {
        const id = parseInt(req.params.id);
        const team = await storage.updateTeam(id, req.body);
        res.json(team);
      } catch (error) {
        console.error("Error updating team:", error);
        res.status(500).json({ message: "Failed to update team" });
      }
    }
  });

  app.delete("/api/teams/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.deleteTeam(id);
      res.json({ message: "Team deleted successfully" });
    } catch (error) {
      console.error("Error deleting team:", error);
      res.status(500).json({ message: "Failed to delete team" });
    }
  });

  // Player routes
  app.get("/api/players", requireAuth, async (req, res) => {
    try {
      const players = await storage.getPlayers();
      res.json(players);
    } catch (error) {
      console.error("Error fetching players:", error);
      res.status(500).json({ message: "Failed to fetch players" });
    }
  });

  app.get("/api/players/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const player = await storage.getPlayer(id);
      if (!player) {
        return res.status(404).json({ message: "Player not found" });
      }
      res.json(player);
    } catch (error) {
      console.error("Error fetching player:", error);
      res.status(500).json({ message: "Failed to fetch player" });
    }
  });

  app.post("/api/players", requireAuth, upload.single("profileImage"), async (req, res) => {
    try {
      console.log("POST /api/players - Raw request body:", req.body);
      console.log("POST /api/players - File:", req.file);
      
      // Convert string values from form data to proper types
      const formData = { ...req.body };
      if (formData.teamId && formData.teamId !== 'undefined') {
        formData.teamId = parseInt(formData.teamId);
      } else {
        delete formData.teamId; // Remove if undefined or invalid
      }
      if (formData.jerseyNumber && formData.jerseyNumber !== 'undefined') {
        formData.jerseyNumber = parseInt(formData.jerseyNumber);
      } else {
        delete formData.jerseyNumber;
      }
      if (formData.height && formData.height !== 'undefined') {
        formData.height = parseInt(formData.height);
      } else {
        delete formData.height;
      }
      if (formData.weight && formData.weight !== 'undefined') {
        formData.weight = parseInt(formData.weight);
      } else {
        delete formData.weight;
      }
      
      // Clean up empty strings
      Object.keys(formData).forEach(key => {
        if (formData[key] === '' || formData[key] === 'undefined') {
          delete formData[key];
        }
      });
      
      console.log("POST /api/players - Processed form data:", formData);
      
      const playerData = insertPlayerSchema.parse(formData);
      console.log("POST /api/players - Validated player data:", playerData);
      
      if (req.file) {
        playerData.profileImageUrl = `/uploads/${req.file.filename}`;
      }
      
      const player = await storage.createPlayer(playerData);
      console.log("POST /api/players - Created player:", player);
      
      res.status(201).json(player);
    } catch (error) {
      if (error instanceof z.ZodError) {
        console.error("POST /api/players - Validation errors:", error.errors);
        return res.status(400).json({ 
          message: "Invalid player data", 
          errors: error.errors.map(err => `${err.path.join('.')}: ${err.message}`)
        });
      }
      console.error("POST /api/players - Server error:", error);
      res.status(500).json({ message: "Failed to create player", error: error.message });
    }
  });

  app.put("/api/players/:id", requireAuth, upload.single("profileImage"), async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const playerData = req.body;
      if (req.file) {
        playerData.profileImageUrl = `/uploads/${req.file.filename}`;
      }
      const player = await storage.updatePlayer(id, playerData);
      res.json(player);
    } catch (error) {
      console.error("Error updating player:", error);
      res.status(500).json({ message: "Failed to update player" });
    }
  });

  app.delete("/api/players/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.deletePlayer(id);
      res.json({ message: "Player deleted successfully" });
    } catch (error) {
      console.error("Error deleting player:", error);
      res.status(500).json({ message: "Failed to delete player" });
    }
  });

  // Coach routes
  app.get("/api/coaches", requireAuth, async (req, res) => {
    try {
      const coaches = await storage.getCoaches();
      res.json(coaches);
    } catch (error) {
      console.error("Error fetching coaches:", error);
      res.status(500).json({ message: "Failed to fetch coaches" });
    }
  });

  app.get("/api/coaches/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const coach = await storage.getCoach(id);
      if (!coach) {
        return res.status(404).json({ message: "Coach not found" });
      }
      res.json(coach);
    } catch (error) {
      console.error("Error fetching coach:", error);
      res.status(500).json({ message: "Failed to fetch coach" });
    }
  });

  app.post("/api/coaches", requireAuth, upload.single("profileImage"), async (req, res) => {
    try {
      // Convert numeric fields from strings to numbers if present
      const processedBody = { ...req.body };
      if (processedBody.organizationId) {
        processedBody.organizationId = parseInt(processedBody.organizationId);
      }
      if (processedBody.experience) {
        processedBody.experience = parseInt(processedBody.experience);
      }
      
      const coachData = insertCoachSchema.parse(processedBody);
      if (req.file) {
        coachData.profileImageUrl = `/uploads/${req.file.filename}`;
      }
      const coach = await storage.createCoach(coachData);
      res.json(coach);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ message: "Invalid coach data", errors: error.errors });
      }
      console.error("Error creating coach:", error);
      res.status(500).json({ message: "Failed to create coach" });
    }
  });

  app.put("/api/coaches/:id", requireAuth, upload.single("profileImage"), async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const coachData = req.body;
      if (req.file) {
        coachData.profileImageUrl = `/uploads/${req.file.filename}`;
      }
      const coach = await storage.updateCoach(id, coachData);
      res.json(coach);
    } catch (error) {
      console.error("Error updating coach:", error);
      res.status(500).json({ message: "Failed to update coach" });
    }
  });

  app.delete("/api/coaches/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.deleteCoach(id);
      res.json({ message: "Coach deleted successfully" });
    } catch (error) {
      console.error("Error deleting coach:", error);
      res.status(500).json({ message: "Failed to delete coach" });
    }
  });

  app.get("/api/coaches/:coachId/teams", requireAuth, async (req, res) => {
    try {
      const coachId = parseInt(req.params.coachId);
      const teams = await storage.getCoachTeams(coachId);
      res.json(teams);
    } catch (error) {
      console.error("Error fetching coach teams:", error);
      res.status(500).json({ message: "Failed to fetch coach teams" });
    }
  });

  // Team-Coach assignment routes
  app.get("/api/teams/:teamId/coaches", requireAuth, async (req, res) => {
    try {
      const teamId = parseInt(req.params.teamId);
      const teamCoaches = await storage.getTeamCoaches(teamId);
      res.json(teamCoaches);
    } catch (error) {
      console.error("Error fetching team coaches:", error);
      res.status(500).json({ message: "Failed to fetch team coaches" });
    }
  });

  app.post("/api/teams/:teamId/coaches", requireAuth, async (req, res) => {
    try {
      const teamId = parseInt(req.params.teamId);
      const assignmentData = insertTeamCoachSchema.parse({
        ...req.body,
        teamId,
        startDate: new Date().toISOString().split('T')[0], // Add current date as start date
      });
      const assignment = await storage.assignCoachToTeam(assignmentData);
      res.json(assignment);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ message: "Invalid assignment data", errors: error.errors });
      }
      console.error("Error assigning coach to team:", error);
      res.status(500).json({ message: "Failed to assign coach to team" });
    }
  });

  app.delete("/api/teams/:teamId/coaches/:coachId", requireAuth, async (req, res) => {
    try {
      const teamId = parseInt(req.params.teamId);
      const coachId = parseInt(req.params.coachId);
      await storage.removeCoachFromTeam(teamId, coachId);
      res.json({ message: "Coach removed from team successfully" });
    } catch (error) {
      console.error("Error removing coach from team:", error);
      res.status(500).json({ message: "Failed to remove coach from team" });
    }
  });

  // Email verification routes
  app.post("/api/send-verification-email", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const baseUrl = `${req.protocol}://${req.get('host')}`;
      
      const emailSent = await sendVerificationEmail(
        user.id,
        user.email,
        user.firstName,
        baseUrl
      );
      
      if (emailSent) {
        res.json({ message: "Verification email sent successfully" });
      } else {
        res.json({ message: "Verification email would be sent (SendGrid not configured)" });
      }
    } catch (error) {
      console.error("Error sending verification email:", error);
      res.status(500).json({ message: "Failed to send verification email" });
    }
  });

  app.get("/api/verify-email", async (req, res) => {
    try {
      const { token } = req.query;
      
      if (!token || typeof token !== 'string') {
        return res.status(400).json({ message: "Invalid verification token" });
      }
      
      const result = await verifyEmail(token);
      
      if (result.success) {
        res.json({ message: result.message });
      } else {
        res.status(400).json({ message: result.message });
      }
    } catch (error) {
      console.error("Error verifying email:", error);
      res.status(500).json({ message: "Email verification failed" });
    }
  });







  // Tournament routes
  app.get("/api/tournaments", requireAuth, async (req, res) => {
    try {
      const tournaments = await storage.getTournaments();
      res.json(tournaments);
    } catch (error) {
      console.error("Error fetching tournaments:", error);
      res.status(500).json({ message: "Failed to fetch tournaments" });
    }
  });

  app.get("/api/tournaments/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const tournament = await storage.getTournament(id);
      if (!tournament) {
        return res.status(404).json({ message: "Tournament not found" });
      }
      res.json(tournament);
    } catch (error) {
      console.error("Error fetching tournament:", error);
      res.status(500).json({ message: "Failed to fetch tournament" });
    }
  });

  app.post("/api/tournaments", requireAuth, async (req, res) => {
    try {
      // Transform date strings to Date objects before validation
      const transformedData = {
        ...req.body,
        startDate: new Date(req.body.startDate),
        endDate: new Date(req.body.endDate),
        entryFee: typeof req.body.entryFee === 'string' ? parseFloat(req.body.entryFee) : req.body.entryFee,
        maxTeams: typeof req.body.maxTeams === 'string' ? parseInt(req.body.maxTeams) : req.body.maxTeams,
      };
      
      const tournamentData = insertTournamentSchema.parse(transformedData);
      const tournament = await storage.createTournament(tournamentData);
      res.status(201).json(tournament);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ message: "Invalid tournament data", errors: error.errors });
      }
      console.error("Error creating tournament:", error);
      res.status(500).json({ message: "Failed to create tournament" });
    }
  });

  app.put("/api/tournaments/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const tournamentData = insertTournamentSchema.partial().parse(req.body);
      const tournament = await storage.updateTournament(id, tournamentData);
      res.json(tournament);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ message: "Invalid tournament data", errors: error.errors });
      }
      console.error("Error updating tournament:", error);
      res.status(500).json({ message: "Failed to update tournament" });
    }
  });

  app.delete("/api/tournaments/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.deleteTournament(id);
      res.json({ message: "Tournament deleted successfully" });
    } catch (error) {
      console.error("Error deleting tournament:", error);
      res.status(500).json({ message: "Failed to delete tournament" });
    }
  });

  // Match routes
  app.get("/api/matches", requireAuth, async (req, res) => {
    try {
      const matches = await storage.getMatches();
      res.json(matches);
    } catch (error) {
      console.error("Error fetching matches:", error);
      res.status(500).json({ message: "Failed to fetch matches" });
    }
  });

  app.get("/api/tournaments/:tournamentId/matches", requireAuth, async (req, res) => {
    try {
      const tournamentId = parseInt(req.params.tournamentId);
      const matches = await storage.getMatchesByTournament(tournamentId);
      res.json(matches);
    } catch (error) {
      console.error("Error fetching tournament matches:", error);
      res.status(500).json({ message: "Failed to fetch tournament matches" });
    }
  });

  app.post("/api/matches", requireAuth, async (req, res) => {
    try {
      const matchData = insertMatchSchema.parse(req.body);
      const match = await storage.createMatch(matchData);
      res.status(201).json(match);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ message: "Invalid match data", errors: error.errors });
      }
      console.error("Error creating match:", error);
      res.status(500).json({ message: "Failed to create match" });
    }
  });

  app.put("/api/matches/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const matchData = insertMatchSchema.partial().parse(req.body);
      const match = await storage.updateMatch(id, matchData);
      res.json(match);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return res.status(400).json({ message: "Invalid match data", errors: error.errors });
      }
      console.error("Error updating match:", error);
      res.status(500).json({ message: "Failed to update match" });
    }
  });

  app.delete("/api/matches/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.deleteMatch(id);
      res.json({ message: "Match deleted successfully" });
    } catch (error) {
      console.error("Error deleting match:", error);
      res.status(500).json({ message: "Failed to delete match" });
    }
  });

  // Smart Onboarding API endpoints
  app.get("/api/onboarding/progress", requireAuth, async (req, res) => {
    try {
      const userId = req.user?.id;
      const organizationId = req.query.organizationId as string;
      
      // Calculate onboarding progress based on completed setup steps
      const teams = await storage.getTeams();
      const players = await storage.getPlayers();
      const coaches = await storage.getCoaches();
      
      const totalSteps = 6;
      let completedSteps = 0;
      
      // Check if basic setup is completed
      if (teams.length > 0) completedSteps++;
      if (players.length > 0) completedSteps++;
      if (coaches.length > 0) completedSteps++;
      
      // Additional setup checks
      const hasRoster = players.some(p => p.position);
      if (hasRoster) completedSteps++;
      
      const hasAttendance = true; // Simplified check
      if (hasAttendance) completedSteps++;
      
      const hasAnalytics = true; // Simplified check
      if (hasAnalytics) completedSteps++;
      
      const progress = {
        totalSteps,
        completedSteps,
        recommendedNext: getRecommendedNextSteps(completedSteps),
        timeToComplete: calculateTimeToComplete(totalSteps - completedSteps)
      };
      
      res.json(progress);
    } catch (error) {
      console.error("Error fetching onboarding progress:", error);
      res.status(500).json({ message: "Failed to fetch onboarding progress" });
    }
  });

  function getRecommendedNextSteps(completedSteps: number): string[] {
    const allSteps = [
      "Create your first team",
      "Add players to your roster",
      "Assign coaches",
      "Set up formations",
      "Configure attendance tracking",
      "Enable analytics dashboard"
    ];
    
    return allSteps.slice(completedSteps, completedSteps + 2);
  }

  function calculateTimeToComplete(remainingSteps: number): string {
    const avgTimePerStep = 15; // minutes
    const totalMinutes = remainingSteps * avgTimePerStep;
    
    if (totalMinutes < 60) {
      return `${totalMinutes} min`;
    } else {
      const hours = Math.floor(totalMinutes / 60);
      const minutes = totalMinutes % 60;
      return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
    }
  }

  // Smart onboarding recommendations endpoint
  app.get("/api/onboarding/smart-recommendations", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const sportType = req.query.sport || user.sport || 'rugby';
      
      // Get organization data to analyze current setup
      const teams = await storage.getTeams();
      const allPlayers = await storage.getPlayers();
      const allCoaches = await storage.getCoaches();
      
      // Import the smart recommendation engine
      const { SmartRecommendationEngine } = await import("./smart-recommendations-engine");
      
      // Initialize the AI recommendation engine
      const engine = new SmartRecommendationEngine(teams, allPlayers, allCoaches, user);
      
      // Generate intelligent sport-specific recommendations
      const result = engine.generateRecommendations(sportType);
      
      const completedCount = result.recommendations.filter(r => r.completed).length;
      const completionPercentage = Math.round((completedCount / result.recommendations.length) * 100);
      
      res.json({
        ...result.analysis,
        recommendations: result.recommendations,
        completionPercentage,
        completedCount,
        totalCount: result.recommendations.length,
        nextPriorityAction: result.recommendations.find(r => !r.completed && r.priority === "critical")?.id || 
                           result.recommendations.find(r => !r.completed && r.priority === "high")?.id || null,
        aiInsights: result.analysis.keyInsights,
        readinessScore: result.analysis.currentSetupScore,
        nextMilestone: result.analysis.nextMilestone
      });
    } catch (error) {
      console.error("Error fetching smart recommendations:", error);
      res.status(500).json({ message: "Failed to fetch smart recommendations" });
    }
  });

  // Track recommendation completion
  app.post("/api/onboarding/complete-recommendation", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const { recommendationId, timestamp } = req.body;
      
      // In a real implementation, you'd store this in a user_onboarding_progress table
      // For now, we'll just acknowledge the completion
      
      res.json({
        success: true,
        recommendationId,
        completedAt: timestamp || new Date().toISOString(),
        message: "Recommendation marked as completed"
      });
    } catch (error) {
      console.error("Error completing recommendation:", error);
      res.status(500).json({ message: "Failed to complete recommendation" });
    }
  });




  // Smart Onboarding Routes
  app.get("/api/smart-onboarding", requireAuth, async (req: Request, res: Response) => {
    try {
      const { sport } = req.query;
      if (!sport || typeof sport !== 'string') {
        return res.status(400).json({ message: "Sport parameter is required" });
      }
      
      const userId = req.user.id;
      const onboardingData = await getSmartOnboardingData(userId, sport);
      res.json(onboardingData);
    } catch (error) {
      console.error("Error getting smart onboarding data:", error);
      res.status(500).json({ message: "Failed to get onboarding recommendations" });
    }
  });

  app.post("/api/smart-onboarding/complete", requireAuth, async (req: Request, res: Response) => {
    try {
      const { recommendationId } = req.body;
      if (!recommendationId) {
        return res.status(400).json({ message: "Recommendation ID is required" });
      }
      
      // In a real implementation, you would save the completion status to the database
      res.json({ 
        success: true, 
        message: "Recommendation marked as completed",
        recommendationId,
        completedAt: new Date().toISOString()
      });
    } catch (error) {
      console.error("Error completing recommendation:", error);
      res.status(500).json({ message: "Failed to complete recommendation" });
    }
  });

  // Video Highlights API endpoints
  app.get("/api/video-highlights/library", requireAuth, getVideoLibrary);
  app.post("/api/video-highlights/upload", requireAuth, videoUpload.single('video'), uploadVideo);
  app.post("/api/video-highlights/analyze", requireAuth, analyzeVideo);
  app.get("/api/video-highlights/analysis/:videoId", requireAuth, getAnalysisStatus);
  app.post("/api/video-highlights/generate", requireAuth, generateHighlights);
  app.delete("/api/video-highlights/:videoId", requireAuth, deleteVideo);

  // Super Admin API endpoints
  app.get("/api/superadmin/organizations", requireSuperAdmin, async (req, res) => {
    try {
      const organizations = await storage.getAllOrganizations();
      res.json(organizations);
    } catch (error) {
      console.error("Error fetching organizations:", error);
      res.status(500).json({ message: "Failed to fetch organizations" });
    }
  });

  app.get("/api/superadmin/modules", requireSuperAdmin, async (req, res) => {
    try {
      const modules = await storage.getAllModules();
      res.json(modules);
    } catch (error) {
      console.error("Error fetching modules:", error);
      res.status(500).json({ message: "Failed to fetch modules" });
    }
  });

  app.get("/api/superadmin/plans", requireSuperAdmin, async (req, res) => {
    try {
      const plans = await storage.getAllSubscriptionPlans();
      res.json(plans);
    } catch (error) {
      console.error("Error fetching subscription plans:", error);
      res.status(500).json({ message: "Failed to fetch subscription plans" });
    }
  });

  app.get("/api/superadmin/organizations/:id/modules", requireSuperAdmin, async (req, res) => {
    try {
      const orgId = parseInt(req.params.id);
      const permissions = await storage.getOrganizationModulePermissions(orgId);
      res.json(permissions);
    } catch (error) {
      console.error("Error fetching organization modules:", error);
      res.status(500).json({ message: "Failed to fetch organization modules" });
    }
  });

  app.put("/api/superadmin/organizations/:id/subscription", requireSuperAdmin, async (req, res) => {
    try {
      const orgId = parseInt(req.params.id);
      const { subscriptionTier, subscriptionStatus } = req.body;
      await storage.updateOrganizationSubscription(orgId, { subscriptionTier, subscriptionStatus });
      res.json({ success: true });
    } catch (error) {
      console.error("Error updating subscription:", error);
      res.status(500).json({ message: "Failed to update subscription" });
    }
  });

  app.put("/api/superadmin/organizations/:orgId/modules/:moduleId", requireSuperAdmin, async (req, res) => {
    try {
      const orgId = parseInt(req.params.orgId);
      const moduleId = parseInt(req.params.moduleId);
      const { enabled } = req.body;
      await storage.updateOrganizationModulePermission(orgId, moduleId, enabled);
      res.json({ success: true });
    } catch (error) {
      console.error("Error updating module permission:", error);
      res.status(500).json({ message: "Failed to update module permission" });
    }
  });

  app.post("/api/superadmin/modules", requireSuperAdmin, async (req, res) => {
    try {
      const module = await storage.createModule(req.body);
      res.json(module);
    } catch (error) {
      console.error("Error creating module:", error);
      res.status(500).json({ message: "Failed to create module" });
    }
  });

  app.get("/api/modules", requireSuperAdmin, async (req, res) => {
    try {
      const modules = await storage.getModules();
      res.json(modules);
    } catch (error) {
      console.error("Error fetching modules:", error);
      res.status(500).json({ message: "Failed to fetch modules" });
    }
  });

  app.get("/api/modules/:id", requireSuperAdmin, async (req, res) => {
    try {
      const module = await storage.getModule(parseInt(req.params.id));
      if (!module) {
        return res.status(404).json({ message: "Module not found" });
      }
      res.json(module);
    } catch (error) {
      console.error("Error fetching module:", error);
      res.status(500).json({ message: "Failed to fetch module" });
    }
  });

  app.put("/api/modules/:id", requireSuperAdmin, async (req, res) => {
    try {
      const module = await storage.updateModule(parseInt(req.params.id), req.body);
      res.json(module);
    } catch (error) {
      console.error("Error updating module:", error);
      res.status(500).json({ message: "Failed to update module" });
    }
  });

  app.post("/api/superadmin/organizations", requireSuperAdmin, async (req, res) => {
    try {
      const organization = await storage.createOrganization(req.body);
      res.json(organization);
    } catch (error) {
      console.error("Error creating organization:", error);
      res.status(500).json({ message: "Failed to create organization" });
    }
  });

  // Membership Plans API (mapping to subscription plans)
  app.get("/api/membership-plans", async (req, res) => {
    try {
      const plans = await storage.getSubscriptionPlans();
      res.json(plans);
    } catch (error) {
      console.error("Error fetching membership plans:", error);
      res.status(500).json({ message: "Failed to fetch membership plans" });
    }
  });

  app.get("/api/membership-plans/active", async (req, res) => {
    try {
      const plans = await storage.getActiveSubscriptionPlans();
      res.json(plans);
    } catch (error) {
      console.error("Error fetching active membership plans:", error);
      res.status(500).json({ message: "Failed to fetch active membership plans" });
    }
  });

  app.get("/api/membership-plans/:id", requireAuth, async (req, res) => {
    try {
      const plan = await storage.getSubscriptionPlan(parseInt(req.params.id));
      if (!plan) {
        return res.status(404).json({ message: "Membership plan not found" });
      }
      res.json(plan);
    } catch (error) {
      console.error("Error fetching membership plan:", error);
      res.status(500).json({ message: "Failed to fetch membership plan" });
    }
  });

  app.post("/api/membership-plans", async (req, res) => {
    try {
      const planData = insertSubscriptionPlanSchema.parse(req.body);
      const plan = await storage.createSubscriptionPlan(planData);
      res.status(201).json(plan);
    } catch (error) {
      console.error("Error creating membership plan:", error);
      res.status(500).json({ message: "Failed to create membership plan" });
    }
  });

  app.put("/api/membership-plans/:id", async (req, res) => {
    try {
      const planData = insertSubscriptionPlanSchema.partial().parse(req.body);
      const plan = await storage.updateSubscriptionPlan(parseInt(req.params.id), planData);
      res.json(plan);
    } catch (error) {
      console.error("Error updating membership plan:", error);
      res.status(500).json({ message: "Failed to update membership plan" });
    }
  });

  app.delete("/api/membership-plans/:id", async (req, res) => {
    try {
      await storage.deleteSubscriptionPlan(parseInt(req.params.id));
      res.status(204).send();
    } catch (error) {
      console.error("Error deleting membership plan:", error);
      res.status(500).json({ message: "Failed to delete membership plan" });
    }
  });

  // Subscription Statistics
  app.get("/api/subscription-stats", async (req, res) => {
    try {
      const stats = await storage.getSubscriptionStats();
      res.json(stats);
    } catch (error) {
      console.error("Error fetching subscription stats:", error);
      res.status(500).json({ message: "Failed to fetch subscription stats" });
    }
  });

  // Subscriptions
  app.get("/api/subscriptions", async (req, res) => {
    try {
      const subscriptions = await storage.getSubscriptions();
      res.json(subscriptions);
    } catch (error) {
      console.error("Error fetching subscriptions:", error);
      res.status(500).json({ message: "Failed to fetch subscriptions" });
    }
  });

  app.get("/api/subscriptions/overdue", async (req, res) => {
    try {
      const subscriptions = await storage.getOverdueSubscriptions();
      res.json(subscriptions);
    } catch (error) {
      console.error("Error fetching overdue subscriptions:", error);
      res.status(500).json({ message: "Failed to fetch overdue subscriptions" });
    }
  });

  app.get("/api/subscriptions/expiring/:days", async (req, res) => {
    try {
      const days = parseInt(req.params.days);
      const subscriptions = await storage.getExpiringSubscriptions(days);
      res.json(subscriptions);
    } catch (error) {
      console.error("Error fetching expiring subscriptions:", error);
      res.status(500).json({ message: "Failed to fetch expiring subscriptions" });
    }
  });

  app.post("/api/subscriptions/:id/cancel", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const { reason } = req.body;
      const subscription = await storage.cancelSubscription(id, reason);
      res.json(subscription);
    } catch (error) {
      console.error("Error cancelling subscription:", error);
      res.status(500).json({ message: "Failed to cancel subscription" });
    }
  });

  app.post("/api/subscriptions/:id/suspend", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const { reason } = req.body;
      const subscription = await storage.suspendSubscription(id, reason);
      res.json(subscription);
    } catch (error) {
      console.error("Error suspending subscription:", error);
      res.status(500).json({ message: "Failed to suspend subscription" });
    }
  });

  app.post("/api/subscriptions/:id/reactivate", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const subscription = await storage.reactivateSubscription(id);
      res.json(subscription);
    } catch (error) {
      console.error("Error reactivating subscription:", error);
      res.status(500).json({ message: "Failed to reactivate subscription" });
    }
  });

  // Payments
  app.get("/api/payments", async (req, res) => {
    try {
      const payments = await storage.getPayments();
      res.json(payments);
    } catch (error) {
      console.error("Error fetching payments:", error);
      res.status(500).json({ message: "Failed to fetch payments" });
    }
  });

  // Branding settings routes
  app.get("/api/branding-settings", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const organizationId = user.organizationId;
      
      if (!organizationId) {
        return res.status(400).json({ message: "User not associated with an organization" });
      }
      
      const settings = await storage.getBrandingSettings(organizationId);
      res.json(settings || {});
    } catch (error) {
      console.error("Error fetching branding settings:", error);
      res.status(500).json({ message: "Failed to fetch branding settings" });
    }
  });

  app.post("/api/branding-settings", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const organizationId = user.organizationId;
      
      if (!organizationId) {
        return res.status(400).json({ message: "User not associated with an organization" });
      }
      
      const settingsData = { ...req.body, organizationId };
      const settings = await storage.upsertBrandingSettings(organizationId, settingsData);
      res.json(settings);
    } catch (error) {
      console.error("Error updating branding settings:", error);
      res.status(500).json({ message: "Failed to update branding settings" });
    }
  });

  // Register theme and payment gateway routes
  registerThemeRoutes(app);
  registerCmsRoutes(app);

  // Notification routes
  app.get("/api/notifications", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const limit = parseInt(req.query.limit as string) || 50;
      const notifications = await storage.getNotifications(user.id, limit);
      res.json(notifications);
    } catch (error) {
      console.error("Error fetching notifications:", error);
      res.status(500).json({ message: "Failed to fetch notifications" });
    }
  });

  app.get("/api/notifications/unread", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const notifications = await storage.getUnreadNotifications(user.id);
      res.json(notifications);
    } catch (error) {
      console.error("Error fetching unread notifications:", error);
      res.status(500).json({ message: "Failed to fetch unread notifications" });
    }
  });

  app.post("/api/notifications/:id/read", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.markNotificationAsRead(id);
      res.json({ success: true });
    } catch (error) {
      console.error("Error marking notification as read:", error);
      res.status(500).json({ message: "Failed to mark notification as read" });
    }
  });

  app.post("/api/notifications/read-all", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      await storage.markAllNotificationsAsRead(user.id);
      res.json({ success: true });
    } catch (error) {
      console.error("Error marking all notifications as read:", error);
      res.status(500).json({ message: "Failed to mark all notifications as read" });
    }
  });

  app.delete("/api/notifications/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.deleteNotification(id);
      res.json({ success: true });
    } catch (error) {
      console.error("Error deleting notification:", error);
      res.status(500).json({ message: "Failed to delete notification" });
    }
  });

  // User preferences routes
  app.get("/api/user/preferences", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const preferences = await storage.getUserPreferences(user.id);
      res.json(preferences);
    } catch (error) {
      console.error("Error fetching user preferences:", error);
      res.status(500).json({ message: "Failed to fetch user preferences" });
    }
  });

  app.put("/api/user/preferences", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const updated = await storage.updateUserPreferences(user.id, req.body);
      res.json(updated);
    } catch (error) {
      console.error("Error updating user preferences:", error);
      res.status(500).json({ message: "Failed to update user preferences" });
    }
  });

  app.put("/api/user/profile", requireAuth, upload.single("profileImage"), async (req, res) => {
    try {
      const user = req.user as any;
      const updateData: any = {
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        email: req.body.email,
      };

      if (req.file) {
        updateData.profileImageUrl = `/uploads/${req.file.filename}`;
      }

      const updated = await storage.updateUser(user.id, updateData);
      res.json(updated);
    } catch (error) {
      console.error("Error updating profile:", error);
      res.status(500).json({ message: "Failed to update profile" });
    }
  });

  app.post("/api/user/change-password", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const { currentPassword, newPassword } = req.body;
      
      // Verify current password (implement this in storage)
      const isValid = await storage.verifyPassword(user.id, currentPassword);
      
      if (!isValid) {
        return res.status(400).json({ message: "Current password is incorrect" });
      }

      // Hash and update new password
      const hashedPassword = await hashPassword(newPassword);
      await storage.updateUser(user.id, { password: hashedPassword });
      
      res.json({ success: true });
    } catch (error) {
      console.error("Error changing password:", error);
      res.status(500).json({ message: "Failed to change password" });
    }
  });

  app.get("/api/user/subscription", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      // Get user subscription details
      const subscription = {
        tier: user.subscriptionTier || "Regular",
        status: user.subscriptionStatus || "inactive",
        stripeSubscriptionId: user.stripeSubscriptionId,
        subscriptionEndDate: user.subscriptionEndDate,
      };
      res.json(subscription);
    } catch (error) {
      console.error("Error fetching subscription:", error);
      res.status(500).json({ message: "Failed to fetch subscription" });
    }
  });

  // Reports routes
  app.get("/api/reports/fixtures", requireAuth, async (req, res) => {
    try {
      const filters: any = {};
      
      if (req.query.organizationId) filters.organizationId = parseInt(req.query.organizationId as string);
      if (req.query.teamId) filters.teamId = parseInt(req.query.teamId as string);
      if (req.query.startDate) filters.startDate = new Date(req.query.startDate as string);
      if (req.query.endDate) filters.endDate = new Date(req.query.endDate as string);

      const report = await reportsService.getFixturesReport(filters);
      res.json(report);
    } catch (error) {
      console.error("Error generating fixtures report:", error);
      res.status(500).json({ message: "Failed to generate fixtures report" });
    }
  });

  app.get("/api/reports/attendance", requireAuth, async (req, res) => {
    try {
      const filters: any = {};
      
      if (req.query.organizationId) filters.organizationId = parseInt(req.query.organizationId as string);
      if (req.query.teamId) filters.teamId = parseInt(req.query.teamId as string);
      if (req.query.startDate) filters.startDate = new Date(req.query.startDate as string);
      if (req.query.endDate) filters.endDate = new Date(req.query.endDate as string);

      const report = await reportsService.getAttendanceReport(filters);
      res.json(report);
    } catch (error) {
      console.error("Error generating attendance report:", error);
      res.status(500).json({ message: "Failed to generate attendance report" });
    }
  });

  app.get("/api/reports/revenue", requireAuth, async (req, res) => {
    try {
      const filters: any = {};
      
      if (req.query.organizationId) filters.organizationId = parseInt(req.query.organizationId as string);
      if (req.query.startDate) filters.startDate = new Date(req.query.startDate as string);
      if (req.query.endDate) filters.endDate = new Date(req.query.endDate as string);

      const report = await reportsService.getRevenueReport(filters);
      res.json(report);
    } catch (error) {
      console.error("Error generating revenue report:", error);
      res.status(500).json({ message: "Failed to generate revenue report" });
    }
  });

  app.get("/api/reports/top-scorers", requireAuth, async (req, res) => {
    try {
      const filters: any = {};
      
      if (req.query.organizationId) filters.organizationId = parseInt(req.query.organizationId as string);
      if (req.query.teamId) filters.teamId = parseInt(req.query.teamId as string);
      if (req.query.limit) filters.limit = parseInt(req.query.limit as string);

      const report = await reportsService.getTopScorersReport(filters);
      res.json(report);
    } catch (error) {
      console.error("Error generating top scorers report:", error);
      res.status(500).json({ message: "Failed to generate top scorers report" });
    }
  });

  app.get("/api/reports/export/:type", requireAuth, async (req, res) => {
    try {
      const reportType = req.params.type;
      let reportData: any;

      switch (reportType) {
        case 'fixtures':
          reportData = await reportsService.getFixturesReport();
          break;
        case 'attendance':
          reportData = await reportsService.getAttendanceReport();
          break;
        case 'revenue':
          reportData = await reportsService.getRevenueReport();
          break;
        case 'top-scorers':
          reportData = await reportsService.getTopScorersReport();
          break;
        default:
          return res.status(400).json({ message: "Invalid report type" });
      }

      const csv = await reportsService.exportReportToCSV(reportType, reportData);
      
      res.setHeader('Content-Type', 'text/csv');
      res.setHeader('Content-Disposition', `attachment; filename="${reportType}-report-${new Date().toISOString().split('T')[0]}.csv"`);
      res.send(csv);
    } catch (error) {
      console.error("Error exporting report:", error);
      res.status(500).json({ message: "Failed to export report" });
    }
  });

  // Audit log routes
  app.get("/api/audit-logs", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      
      // Check if user has admin access
      if (user.role !== 'superadmin' && user.role !== 'org_admin') {
        return res.status(403).json({ message: "Admin access required" });
      }

      const filters: any = {
        limit: parseInt(req.query.limit as string) || 100,
      };

      // Superadmin can see all logs, org_admin sees only their organization
      if (user.role === 'org_admin' && user.organizationId) {
        filters.organizationId = user.organizationId;
      }

      if (req.query.userId) filters.userId = req.query.userId as string;
      if (req.query.resource) filters.resource = req.query.resource as string;
      if (req.query.action) filters.action = req.query.action as string;
      if (req.query.startDate) filters.startDate = new Date(req.query.startDate as string);
      if (req.query.endDate) filters.endDate = new Date(req.query.endDate as string);

      const logs = await storage.getAuditLogs(filters);
      res.json(logs);
    } catch (error) {
      console.error("Error fetching audit logs:", error);
      res.status(500).json({ message: "Failed to fetch audit logs" });
    }
  });

  app.get("/api/audit-logs/:id", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      
      // Check if user has admin access
      if (user.role !== 'superadmin' && user.role !== 'org_admin') {
        return res.status(403).json({ message: "Admin access required" });
      }

      const id = parseInt(req.params.id);
      const log = await storage.getAuditLog(id);
      
      if (!log) {
        return res.status(404).json({ message: "Audit log not found" });
      }

      // Org admin can only see logs from their organization
      if (user.role === 'org_admin' && log.organizationId !== user.organizationId) {
        return res.status(403).json({ message: "Access denied" });
      }

      res.json(log);
    } catch (error) {
      console.error("Error fetching audit log:", error);
      res.status(500).json({ message: "Failed to fetch audit log" });
    }
  });

  // ========== LEAGUES ROUTES ==========
  app.get("/api/leagues", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const organizationId = user.role === 'superadmin' ? undefined : user.organizationId;
      const leagues = await storage.getLeagues(organizationId);
      res.json(leagues);
    } catch (error) {
      console.error("Error fetching leagues:", error);
      res.status(500).json({ message: "Failed to fetch leagues" });
    }
  });

  app.get("/api/leagues/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const league = await storage.getLeague(id);
      
      if (!league) {
        return res.status(404).json({ message: "League not found" });
      }

      res.json(league);
    } catch (error) {
      console.error("Error fetching league:", error);
      res.status(500).json({ message: "Failed to fetch league" });
    }
  });

  app.post("/api/leagues", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const validation = insertLeagueSchema.safeParse(req.body);
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const leagueData = {
        ...validation.data,
        organizationId: user.organizationId,
      };

      const league = await storage.createLeague(leagueData);
      res.status(201).json(league);
    } catch (error) {
      console.error("Error creating league:", error);
      res.status(500).json({ message: "Failed to create league" });
    }
  });

  app.put("/api/leagues/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const validation = insertLeagueSchema.partial().safeParse(req.body);
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const league = await storage.updateLeague(id, validation.data);
      res.json(league);
    } catch (error) {
      console.error("Error updating league:", error);
      res.status(500).json({ message: "Failed to update league" });
    }
  });

  app.delete("/api/leagues/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.deleteLeague(id);
      res.json({ message: "League deleted successfully" });
    } catch (error) {
      console.error("Error deleting league:", error);
      res.status(500).json({ message: "Failed to delete league" });
    }
  });

  app.get("/api/leagues/:id/standings", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const standings = await storage.getLeagueStandings(id);
      res.json(standings);
    } catch (error) {
      console.error("Error fetching league standings:", error);
      res.status(500).json({ message: "Failed to fetch league standings" });
    }
  });

  // ========== LEAGUE TEAMS ROUTES ==========
  app.post("/api/league-teams", requireAuth, async (req, res) => {
    try {
      const validation = insertLeagueTeamSchema.safeParse(req.body);
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const leagueTeam = await storage.addTeamToLeague(validation.data);
      res.status(201).json(leagueTeam);
    } catch (error) {
      console.error("Error adding team to league:", error);
      res.status(500).json({ message: "Failed to add team to league" });
    }
  });

  app.delete("/api/league-teams/:leagueId/:teamId", requireAuth, async (req, res) => {
    try {
      const leagueId = parseInt(req.params.leagueId);
      const teamId = parseInt(req.params.teamId);
      await storage.removeTeamFromLeague(leagueId, teamId);
      res.json({ message: "Team removed from league successfully" });
    } catch (error) {
      console.error("Error removing team from league:", error);
      res.status(500).json({ message: "Failed to remove team from league" });
    }
  });

  app.patch("/api/league-teams/:leagueId/:teamId", requireAuth, async (req, res) => {
    try {
      const leagueId = parseInt(req.params.leagueId);
      const teamId = parseInt(req.params.teamId);
      const validation = insertLeagueTeamSchema.partial().safeParse(req.body);
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const leagueTeam = await storage.updateLeagueTeamStats(leagueId, teamId, validation.data);
      res.json(leagueTeam);
    } catch (error) {
      console.error("Error updating league team stats:", error);
      res.status(500).json({ message: "Failed to update league team stats" });
    }
  });

  // ========== VENUES ROUTES ==========
  app.get("/api/venues", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const organizationId = user.role === 'superadmin' ? undefined : user.organizationId;
      const venues = await storage.getVenues(organizationId);
      res.json(venues);
    } catch (error) {
      console.error("Error fetching venues:", error);
      res.status(500).json({ message: "Failed to fetch venues" });
    }
  });

  app.get("/api/venues/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const venue = await storage.getVenue(id);
      
      if (!venue) {
        return res.status(404).json({ message: "Venue not found" });
      }

      res.json(venue);
    } catch (error) {
      console.error("Error fetching venue:", error);
      res.status(500).json({ message: "Failed to fetch venue" });
    }
  });

  app.post("/api/venues", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const validation = insertVenueSchema.safeParse(req.body);
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const venueData = {
        ...validation.data,
        organizationId: user.organizationId,
      };

      const venue = await storage.createVenue(venueData);
      res.status(201).json(venue);
    } catch (error) {
      console.error("Error creating venue:", error);
      res.status(500).json({ message: "Failed to create venue" });
    }
  });

  app.put("/api/venues/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const validation = insertVenueSchema.partial().safeParse(req.body);
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const venue = await storage.updateVenue(id, validation.data);
      res.json(venue);
    } catch (error) {
      console.error("Error updating venue:", error);
      res.status(500).json({ message: "Failed to update venue" });
    }
  });

  app.delete("/api/venues/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.deleteVenue(id);
      res.json({ message: "Venue deleted successfully" });
    } catch (error) {
      console.error("Error deleting venue:", error);
      res.status(500).json({ message: "Failed to delete venue" });
    }
  });

  // ========== REFEREES ROUTES ==========
  app.get("/api/referees", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const organizationId = user.role === 'superadmin' ? undefined : user.organizationId;
      const referees = await storage.getReferees(organizationId);
      res.json(referees);
    } catch (error) {
      console.error("Error fetching referees:", error);
      res.status(500).json({ message: "Failed to fetch referees" });
    }
  });

  app.get("/api/referees/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const referee = await storage.getReferee(id);
      
      if (!referee) {
        return res.status(404).json({ message: "Referee not found" });
      }

      res.json(referee);
    } catch (error) {
      console.error("Error fetching referee:", error);
      res.status(500).json({ message: "Failed to fetch referee" });
    }
  });

  app.post("/api/referees", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const validation = insertRefereeSchema.safeParse(req.body);
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const refereeData = {
        ...validation.data,
        organizationId: user.organizationId,
      };

      const referee = await storage.createReferee(refereeData);
      res.status(201).json(referee);
    } catch (error) {
      console.error("Error creating referee:", error);
      res.status(500).json({ message: "Failed to create referee" });
    }
  });

  app.put("/api/referees/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const validation = insertRefereeSchema.partial().safeParse(req.body);
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const referee = await storage.updateReferee(id, validation.data);
      res.json(referee);
    } catch (error) {
      console.error("Error updating referee:", error);
      res.status(500).json({ message: "Failed to update referee" });
    }
  });

  app.delete("/api/referees/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.deleteReferee(id);
      res.json({ message: "Referee deleted successfully" });
    } catch (error) {
      console.error("Error deleting referee:", error);
      res.status(500).json({ message: "Failed to delete referee" });
    }
  });

  // ========== FIXTURES ROUTES ==========
  app.get("/api/fixtures", requireAuth, async (req, res) => {
    try {
      const filters: any = {};
      
      if (req.query.leagueId) filters.leagueId = parseInt(req.query.leagueId as string);
      if (req.query.tournamentId) filters.tournamentId = parseInt(req.query.tournamentId as string);
      if (req.query.status) filters.status = req.query.status as string;

      const fixtures = await storage.getFixtures(filters);
      res.json(fixtures);
    } catch (error) {
      console.error("Error fetching fixtures:", error);
      res.status(500).json({ message: "Failed to fetch fixtures" });
    }
  });

  app.get("/api/fixtures/upcoming", requireAuth, async (req, res) => {
    try {
      const limit = req.query.limit ? parseInt(req.query.limit as string) : undefined;
      const fixtures = await storage.getUpcomingFixtures(limit);
      res.json(fixtures);
    } catch (error) {
      console.error("Error fetching upcoming fixtures:", error);
      res.status(500).json({ message: "Failed to fetch upcoming fixtures" });
    }
  });

  app.get("/api/fixtures/live", requireAuth, async (req, res) => {
    try {
      const fixtures = await storage.getLiveFixtures();
      res.json(fixtures);
    } catch (error) {
      console.error("Error fetching live fixtures:", error);
      res.status(500).json({ message: "Failed to fetch live fixtures" });
    }
  });

  app.get("/api/fixtures/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const fixture = await storage.getFixture(id);
      
      if (!fixture) {
        return res.status(404).json({ message: "Fixture not found" });
      }

      res.json(fixture);
    } catch (error) {
      console.error("Error fetching fixture:", error);
      res.status(500).json({ message: "Failed to fetch fixture" });
    }
  });

  app.post("/api/fixtures", requireAuth, async (req, res) => {
    try {
      const validation = insertFixtureSchema.safeParse(req.body);
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const fixture = await storage.createFixture(validation.data);
      res.status(201).json(fixture);
    } catch (error) {
      console.error("Error creating fixture:", error);
      res.status(500).json({ message: "Failed to create fixture" });
    }
  });

  app.put("/api/fixtures/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const validation = insertFixtureSchema.partial().safeParse(req.body);
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const fixture = await storage.updateFixture(id, validation.data);
      res.json(fixture);
    } catch (error) {
      console.error("Error updating fixture:", error);
      res.status(500).json({ message: "Failed to update fixture" });
    }
  });

  app.delete("/api/fixtures/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.deleteFixture(id);
      res.json({ message: "Fixture deleted successfully" });
    } catch (error) {
      console.error("Error deleting fixture:", error);
      res.status(500).json({ message: "Failed to delete fixture" });
    }
  });

  // ========== MATCH EVENTS ROUTES ==========
  app.get("/api/fixtures/:fixtureId/events", requireAuth, async (req, res) => {
    try {
      const fixtureId = parseInt(req.params.fixtureId);
      const events = await storage.getMatchEvents(fixtureId);
      res.json(events);
    } catch (error) {
      console.error("Error fetching match events:", error);
      res.status(500).json({ message: "Failed to fetch match events" });
    }
  });

  app.post("/api/fixtures/:fixtureId/events", requireAuth, async (req, res) => {
    try {
      const fixtureId = parseInt(req.params.fixtureId);
      const validation = insertMatchEventSchema.safeParse({ ...req.body, fixtureId });
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const event = await storage.createMatchEvent(validation.data);
      res.status(201).json(event);
    } catch (error) {
      console.error("Error creating match event:", error);
      res.status(500).json({ message: "Failed to create match event" });
    }
  });

  app.delete("/api/match-events/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await storage.deleteMatchEvent(id);
      res.json({ message: "Match event deleted successfully" });
    } catch (error) {
      console.error("Error deleting match event:", error);
      res.status(500).json({ message: "Failed to delete match event" });
    }
  });

  // ========== MATCH STATISTICS ROUTES ==========
  app.get("/api/fixtures/:fixtureId/statistics", requireAuth, async (req, res) => {
    try {
      const fixtureId = parseInt(req.params.fixtureId);
      const statistics = await storage.getMatchStatistics(fixtureId);
      res.json(statistics);
    } catch (error) {
      console.error("Error fetching match statistics:", error);
      res.status(500).json({ message: "Failed to fetch match statistics" });
    }
  });

  app.post("/api/fixtures/:fixtureId/statistics", requireAuth, async (req, res) => {
    try {
      const fixtureId = parseInt(req.params.fixtureId);
      const validation = insertMatchStatisticsSchema.safeParse({ ...req.body, fixtureId });
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const statistics = await storage.createMatchStatistics(validation.data);
      res.status(201).json(statistics);
    } catch (error) {
      console.error("Error creating match statistics:", error);
      res.status(500).json({ message: "Failed to create match statistics" });
    }
  });

  app.put("/api/match-statistics/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const validation = insertMatchStatisticsSchema.partial().safeParse(req.body);
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const statistics = await storage.updateMatchStatistics(id, validation.data);
      res.json(statistics);
    } catch (error) {
      console.error("Error updating match statistics:", error);
      res.status(500).json({ message: "Failed to update match statistics" });
    }
  });

  // ========== PLAYER TRANSFERS ROUTES ==========
  app.get("/api/player-transfers", requireAuth, async (req, res) => {
    try {
      const filters: any = {};
      
      if (req.query.status) filters.status = req.query.status as string;
      if (req.query.playerId) filters.playerId = parseInt(req.query.playerId as string);

      const transfers = await storage.getPlayerTransfers(filters);
      res.json(transfers);
    } catch (error) {
      console.error("Error fetching player transfers:", error);
      res.status(500).json({ message: "Failed to fetch player transfers" });
    }
  });

  app.get("/api/player-transfers/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const transfer = await storage.getPlayerTransfer(id);
      
      if (!transfer) {
        return res.status(404).json({ message: "Player transfer not found" });
      }

      res.json(transfer);
    } catch (error) {
      console.error("Error fetching player transfer:", error);
      res.status(500).json({ message: "Failed to fetch player transfer" });
    }
  });

  app.post("/api/player-transfers", requireAuth, async (req, res) => {
    try {
      const user = req.user as any;
      const validation = insertPlayerTransferSchema.safeParse({
        ...req.body,
        requestedBy: user.id,
      });
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const transfer = await storage.createPlayerTransfer(validation.data);
      res.status(201).json(transfer);
    } catch (error) {
      console.error("Error creating player transfer:", error);
      res.status(500).json({ message: "Failed to create player transfer" });
    }
  });

  app.put("/api/player-transfers/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const validation = insertPlayerTransferSchema.partial().safeParse(req.body);
      
      if (!validation.success) {
        return res.status(400).json({ message: "Validation failed", errors: validation.error.issues });
      }

      const transfer = await storage.updatePlayerTransfer(id, validation.data);
      res.json(transfer);
    } catch (error) {
      console.error("Error updating player transfer:", error);
      res.status(500).json({ message: "Failed to update player transfer" });
    }
  });

  app.post("/api/player-transfers/:id/approve", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const user = req.user as any;
      
      const transfer = await storage.approvePlayerTransfer(id, user.id);
      res.json(transfer);
    } catch (error) {
      console.error("Error approving player transfer:", error);
      res.status(500).json({ message: "Failed to approve player transfer" });
    }
  });

  app.post("/api/player-transfers/:id/reject", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const { reason } = req.body;
      
      if (!reason) {
        return res.status(400).json({ message: "Rejection reason is required" });
      }
      
      const transfer = await storage.rejectPlayerTransfer(id, reason);
      res.json(transfer);
    } catch (error) {
      console.error("Error rejecting player transfer:", error);
      res.status(500).json({ message: "Failed to reject player transfer" });
    }
  });

  app.post("/api/player-transfers/:id/complete", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const transfer = await storage.completePlayerTransfer(id);
      res.json(transfer);
    } catch (error) {
      console.error("Error completing player transfer:", error);
      res.status(500).json({ message: "Failed to complete player transfer" });
    }
  });

  const httpServer = createServer(app);
  return httpServer;
}