import type { Express, Request, Response } from "express";
import { storage } from "./storage";
import { insertThemeSchema, insertPaymentGatewaySchema } from "@shared/theme-schema";
import { z } from "zod";
import { requireAuth } from "./local-auth";

// Theme management routes
export function registerThemeRoutes(app: Express) {
  // Get all themes
  app.get("/api/themes", async (req: Request, res: Response) => {
    try {
      const themes = await storage.getThemes();
      res.json(themes);
    } catch (error) {
      console.error("Error fetching themes:", error);
      res.status(500).json({ message: "Failed to fetch themes" });
    }
  });

  // Create theme - protected, auth required
  app.post("/api/themes", requireAuth, async (req: Request, res: Response) => {
    try {
      const themeData = insertThemeSchema.parse(req.body);
      const theme = await storage.createTheme(themeData);
      res.status(201).json(theme);
    } catch (error) {
      console.error("Error creating theme:", error);
      if (error instanceof z.ZodError) {
        res.status(400).json({ message: "Invalid theme data", errors: error.errors });
      } else {
        res.status(500).json({ message: "Failed to create theme" });
      }
    }
  });

  // Update theme - protected, auth required
  app.put("/api/themes/:id", requireAuth, async (req: Request, res: Response) => {
    try {
      const id = parseInt(req.params.id);
      const themeData = insertThemeSchema.partial().parse(req.body);
      const theme = await storage.updateTheme(id, themeData);
      res.json(theme);
    } catch (error) {
      console.error("Error updating theme:", error);
      if (error instanceof z.ZodError) {
        res.status(400).json({ message: "Invalid theme data", errors: error.errors });
      } else {
        res.status(500).json({ message: "Failed to update theme" });
      }
    }
  });

  // Delete theme - protected, auth required
  app.delete("/api/themes/:id", requireAuth, async (req: Request, res: Response) => {
    try {
      const id = parseInt(req.params.id);
      await storage.deleteTheme(id);
      res.json({ message: "Theme deleted successfully" });
    } catch (error) {
      console.error("Error deleting theme:", error);
      res.status(500).json({ message: "Failed to delete theme" });
    }
  });

  // Get payment gateways
  app.get("/api/payment-gateways", async (req: Request, res: Response) => {
    try {
      const gateways = await storage.getPaymentGateways();
      res.json(gateways);
    } catch (error) {
      console.error("Error fetching payment gateways:", error);
      res.status(500).json({ message: "Failed to fetch payment gateways" });
    }
  });

  // Create payment gateway - protected, auth required
  app.post("/api/payment-gateways", requireAuth, async (req: Request, res: Response) => {
    try {
      const gatewayData = insertPaymentGatewaySchema.parse(req.body);
      const gateway = await storage.createPaymentGateway(gatewayData);
      res.status(201).json(gateway);
    } catch (error) {
      console.error("Error creating payment gateway:", error);
      if (error instanceof z.ZodError) {
        res.status(400).json({ message: "Invalid gateway data", errors: error.errors });
      } else {
        res.status(500).json({ message: "Failed to create payment gateway" });
      }
    }
  });

  // Update payment gateway - protected, auth required
  app.put("/api/payment-gateways/:id", requireAuth, async (req: Request, res: Response) => {
    try {
      const id = parseInt(req.params.id);
      const gatewayData = insertPaymentGatewaySchema.partial().parse(req.body);
      const gateway = await storage.updatePaymentGateway(id, gatewayData);
      res.json(gateway);
    } catch (error) {
      console.error("Error updating payment gateway:", error);
      if (error instanceof z.ZodError) {
        res.status(400).json({ message: "Invalid gateway data", errors: error.errors });
      } else {
        res.status(500).json({ message: "Failed to update payment gateway" });
      }
    }
  });

  // Test payment gateway connection - protected, auth required
  app.post("/api/payment-gateways/:id/test", requireAuth, async (req: Request, res: Response) => {
    try {
      const id = parseInt(req.params.id);
      const gateway = await storage.getPaymentGateway(id);
      
      if (!gateway) {
        return res.status(404).json({ message: "Payment gateway not found" });
      }

      // Test connection based on provider
      const testResult = await testGatewayConnection(gateway);
      res.json({ success: testResult.success, message: testResult.message });
    } catch (error) {
      console.error("Error testing payment gateway:", error);
      res.status(500).json({ message: "Failed to test payment gateway connection" });
    }
  });

  // Export data - protected, auth required
  app.get("/api/export/:type", requireAuth, async (req: Request, res: Response) => {
    try {
      const { type } = req.params;
      const { format = 'json' } = req.query;
      
      let data;
      switch (type) {
        case 'players':
          data = await storage.getPlayers();
          break;
        case 'teams':
          data = await storage.getTeams();
          break;
        case 'coaches':
          data = await storage.getCoaches();
          break;
        case 'biometric':
          data = await storage.getBiometricData();
          break;
        default:
          return res.status(400).json({ message: "Invalid export type" });
      }

      if (format === 'csv') {
        const csv = convertToCSV(data);
        res.setHeader('Content-Type', 'text/csv');
        res.setHeader('Content-Disposition', `attachment; filename=${type}.csv`);
        res.send(csv);
      } else {
        res.setHeader('Content-Type', 'application/json');
        res.setHeader('Content-Disposition', `attachment; filename=${type}.json`);
        res.json(data);
      }
    } catch (error) {
      console.error("Error exporting data:", error);
      res.status(500).json({ message: "Failed to export data" });
    }
  });

  // Bulk import
  // Import data - protected, auth required
  app.post("/api/import/:type", requireAuth, async (req: Request, res: Response) => {
    try {
      const { type } = req.params;
      const { data, mode = 'create' } = req.body; // mode: 'create', 'update', 'upsert'
      
      let result;
      switch (type) {
        case 'players':
          result = await storage.bulkImportPlayers(data, mode);
          break;
        case 'teams':
          result = await storage.bulkImportTeams(data, mode);
          break;
        case 'coaches':
          result = await storage.bulkImportCoaches(data, mode);
          break;
        default:
          return res.status(400).json({ message: "Invalid import type" });
      }

      res.json(result);
    } catch (error) {
      console.error("Error importing data:", error);
      res.status(500).json({ message: "Failed to import data" });
    }
  });
}

// Helper function to test gateway connections
async function testGatewayConnection(gateway: any): Promise<{ success: boolean; message: string }> {
  try {
    switch (gateway.provider) {
      case 'stripe':
        // Test Stripe connection
        if (!gateway.config.secretKey) {
          return { success: false, message: "Secret key is required" };
        }
        // In a real implementation, you would make an API call to Stripe
        return { success: true, message: "Stripe connection successful" };
        
      case 'paypal':
        // Test PayPal connection
        if (!gateway.config.clientId || !gateway.config.clientSecret) {
          return { success: false, message: "Client ID and secret are required" };
        }
        return { success: true, message: "PayPal connection successful" };
        
      case 'flutterwave':
        // Test Flutterwave connection
        if (!gateway.config.publicKey || !gateway.config.secretKey) {
          return { success: false, message: "Public and secret keys are required" };
        }
        return { success: true, message: "Flutterwave connection successful" };
        
      case 'paystack':
        // Test Paystack connection
        if (!gateway.config.publicKey || !gateway.config.secretKey) {
          return { success: false, message: "Public and secret keys are required" };
        }
        return { success: true, message: "Paystack connection successful" };
        
      case 'razorpay':
        // Test Razorpay connection
        if (!gateway.config.keyId || !gateway.config.keySecret) {
          return { success: false, message: "Key ID and secret are required" };
        }
        return { success: true, message: "Razorpay connection successful" };
        
      default:
        return { success: true, message: "Connection test completed" };
    }
  } catch (error) {
    return { success: false, message: `Connection test failed: ${error.message}` };
  }
}

// Helper function to convert data to CSV
function convertToCSV(data: any[]): string {
  if (!data.length) return '';
  
  const headers = Object.keys(data[0]);
  const csvContent = [
    headers.join(','),
    ...data.map(row => 
      headers.map(header => {
        const value = row[header];
        // Handle nested objects and arrays
        const stringValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
        // Escape quotes and wrap in quotes if contains comma
        return stringValue.includes(',') ? `"${stringValue.replace(/"/g, '""')}"` : stringValue;
      }).join(',')
    )
  ].join('\n');
  
  return csvContent;
}