import type { Express } from "express";
import { cmsStorage } from "./cms-storage";
import { requireAuth } from "./local-auth";
import { 
  insertCmsPageSchema,
  insertCmsContentBlockSchema,
  insertCmsFeatureSchema,
  insertCmsStatSchema,
  insertCmsTestimonialSchema
} from "@shared/schema";

export function registerCmsRoutes(app: Express) {
  // Initialize default content on first run
  app.post("/api/cms/initialize", async (req, res) => {
    try {
      await cmsStorage.initializeDefaultContent();
      res.json({ message: "Default content initialized successfully" });
    } catch (error) {
      console.error("Error initializing CMS content:", error);
      res.status(500).json({ message: "Failed to initialize content" });
    }
  });

  // Public endpoint to get landing page content
  app.get("/api/cms/landing", async (req, res) => {
    try {
      const page = await cmsStorage.getCmsPageBySlug('landing');
      if (!page) {
        return res.status(404).json({ message: "Landing page not found" });
      }

      const [contentBlocks, features, stats, testimonials] = await Promise.all([
        cmsStorage.getCmsContentBlocks(page.id),
        cmsStorage.getCmsFeatures(),
        cmsStorage.getCmsStats(),
        cmsStorage.getCmsTestimonials()
      ]);

      res.json({
        page,
        contentBlocks,
        features,
        stats,
        testimonials
      });
    } catch (error) {
      console.error("Error fetching landing page content:", error);
      res.status(500).json({ message: "Failed to fetch landing page content" });
    }
  });

  // === ADMIN CMS ROUTES ===
  // All admin routes require authentication and admin role

  // Pages Management
  app.get("/api/cms/admin/pages", requireAuth, async (req, res) => {
    try {
      const pages = await cmsStorage.getCmsPages();
      res.json(pages);
    } catch (error) {
      console.error("Error fetching pages:", error);
      res.status(500).json({ message: "Failed to fetch pages" });
    }
  });

  app.get("/api/cms/admin/pages/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const page = await cmsStorage.getCmsPage(id);
      if (!page) {
        return res.status(404).json({ message: "Page not found" });
      }
      
      const contentBlocks = await cmsStorage.getCmsContentBlocks(page.id);
      res.json({ ...page, contentBlocks });
    } catch (error) {
      console.error("Error fetching page:", error);
      res.status(500).json({ message: "Failed to fetch page" });
    }
  });

  app.post("/api/cms/admin/pages", requireAuth, async (req, res) => {
    try {
      const validatedData = insertCmsPageSchema.parse(req.body);
      const page = await cmsStorage.createCmsPage(validatedData);
      res.status(201).json(page);
    } catch (error: any) {
      console.error("Error creating page:", error);
      res.status(400).json({ message: "Failed to create page", error: error.message });
    }
  });

  app.put("/api/cms/admin/pages/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const validatedData = insertCmsPageSchema.partial().parse(req.body);
      const page = await cmsStorage.updateCmsPage(id, validatedData);
      res.json(page);
    } catch (error) {
      console.error("Error updating page:", error);
      res.status(400).json({ message: "Failed to update page", error: error.message });
    }
  });

  app.delete("/api/cms/admin/pages/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await cmsStorage.deleteCmsPage(id);
      res.json({ message: "Page deleted successfully" });
    } catch (error) {
      console.error("Error deleting page:", error);
      res.status(500).json({ message: "Failed to delete page" });
    }
  });

  // Content Blocks Management
  app.post("/api/cms/admin/content-blocks", requireAuth, async (req, res) => {
    try {
      const validatedData = insertCmsContentBlockSchema.parse(req.body);
      const block = await cmsStorage.createCmsContentBlock(validatedData);
      res.status(201).json(block);
    } catch (error) {
      console.error("Error creating content block:", error);
      res.status(400).json({ message: "Failed to create content block", error: error.message });
    }
  });

  app.put("/api/cms/admin/content-blocks/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const validatedData = insertCmsContentBlockSchema.partial().parse(req.body);
      const block = await cmsStorage.updateCmsContentBlock(id, validatedData);
      res.json(block);
    } catch (error) {
      console.error("Error updating content block:", error);
      res.status(400).json({ message: "Failed to update content block", error: error.message });
    }
  });

  app.delete("/api/cms/admin/content-blocks/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await cmsStorage.deleteCmsContentBlock(id);
      res.json({ message: "Content block deleted successfully" });
    } catch (error) {
      console.error("Error deleting content block:", error);
      res.status(500).json({ message: "Failed to delete content block" });
    }
  });

  // Features Management
  app.get("/api/cms/admin/features", requireAuth, async (req, res) => {
    try {
      const features = await cmsStorage.getCmsFeatures();
      res.json(features);
    } catch (error) {
      console.error("Error fetching features:", error);
      res.status(500).json({ message: "Failed to fetch features" });
    }
  });

  app.post("/api/cms/admin/features", requireAuth, async (req, res) => {
    try {
      const validatedData = insertCmsFeatureSchema.parse(req.body);
      const feature = await cmsStorage.createCmsFeature(validatedData);
      res.status(201).json(feature);
    } catch (error) {
      console.error("Error creating feature:", error);
      res.status(400).json({ message: "Failed to create feature", error: error.message });
    }
  });

  app.put("/api/cms/admin/features/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const validatedData = insertCmsFeatureSchema.partial().parse(req.body);
      const feature = await cmsStorage.updateCmsFeature(id, validatedData);
      res.json(feature);
    } catch (error) {
      console.error("Error updating feature:", error);
      res.status(400).json({ message: "Failed to update feature", error: error.message });
    }
  });

  app.delete("/api/cms/admin/features/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await cmsStorage.deleteCmsFeature(id);
      res.json({ message: "Feature deleted successfully" });
    } catch (error) {
      console.error("Error deleting feature:", error);
      res.status(500).json({ message: "Failed to delete feature" });
    }
  });

  // Stats Management
  app.get("/api/cms/admin/stats", requireAuth, async (req, res) => {
    try {
      const stats = await cmsStorage.getCmsStats();
      res.json(stats);
    } catch (error) {
      console.error("Error fetching stats:", error);
      res.status(500).json({ message: "Failed to fetch stats" });
    }
  });

  app.post("/api/cms/admin/stats", requireAuth, async (req, res) => {
    try {
      const validatedData = insertCmsStatSchema.parse(req.body);
      const stat = await cmsStorage.createCmsStat(validatedData);
      res.status(201).json(stat);
    } catch (error) {
      console.error("Error creating stat:", error);
      res.status(400).json({ message: "Failed to create stat", error: error.message });
    }
  });

  app.put("/api/cms/admin/stats/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const validatedData = insertCmsStatSchema.partial().parse(req.body);
      const stat = await cmsStorage.updateCmsStat(id, validatedData);
      res.json(stat);
    } catch (error) {
      console.error("Error updating stat:", error);
      res.status(400).json({ message: "Failed to update stat", error: error.message });
    }
  });

  app.delete("/api/cms/admin/stats/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await cmsStorage.deleteCmsStat(id);
      res.json({ message: "Stat deleted successfully" });
    } catch (error) {
      console.error("Error deleting stat:", error);
      res.status(500).json({ message: "Failed to delete stat" });
    }
  });

  // Testimonials Management
  app.get("/api/cms/admin/testimonials", requireAuth, async (req, res) => {
    try {
      const testimonials = await cmsStorage.getCmsTestimonials();
      res.json(testimonials);
    } catch (error) {
      console.error("Error fetching testimonials:", error);
      res.status(500).json({ message: "Failed to fetch testimonials" });
    }
  });

  app.post("/api/cms/admin/testimonials", requireAuth, async (req, res) => {
    try {
      const validatedData = insertCmsTestimonialSchema.parse(req.body);
      const testimonial = await cmsStorage.createCmsTestimonial(validatedData);
      res.status(201).json(testimonial);
    } catch (error) {
      console.error("Error creating testimonial:", error);
      res.status(400).json({ message: "Failed to create testimonial", error: error.message });
    }
  });

  app.put("/api/cms/admin/testimonials/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      const validatedData = insertCmsTestimonialSchema.partial().parse(req.body);
      const testimonial = await cmsStorage.updateCmsTestimonial(id, validatedData);
      res.json(testimonial);
    } catch (error) {
      console.error("Error updating testimonial:", error);
      res.status(400).json({ message: "Failed to update testimonial", error: error.message });
    }
  });

  app.delete("/api/cms/admin/testimonials/:id", requireAuth, async (req, res) => {
    try {
      const id = parseInt(req.params.id);
      await cmsStorage.deleteCmsTestimonial(id);
      res.json({ message: "Testimonial deleted successfully" });
    } catch (error) {
      console.error("Error deleting testimonial:", error);
      res.status(500).json({ message: "Failed to delete testimonial" });
    }
  });
}