import express, { type Express } from "express";
import { createServer, type Server } from "http";
import { storage } from "./storage";
import { 
  insertProjectTypeSchema, 
  insertLegalStatusSchema, 
  insertCenterSchema, 
  insertCenterServiceSchema, 
  insertMailOfferSchema, 
  insertProjectSchema, 
  insertCompanyConfigSchema,
  insertUserSchema,
  insertTranslationSchema
} from "@shared/schema";
import { z } from "zod";
import { fromZodError } from "zod-validation-error";
import { setupAuth } from "./auth";

export async function registerRoutes(app: Express): Promise<Server> {
  // API routes
  const apiRouter = express.Router();
  
  // Project Types
  apiRouter
    .get("/project-types", async (req, res) => {
      try {
        const projectTypes = await storage.getAllProjectTypes();
        res.json(projectTypes);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching project types" });
      }
    })
    .get("/project-types/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const projectType = await storage.getProjectType(id);
        
        if (!projectType) {
          return res.status(404).json({ message: "Project type not found" });
        }
        
        res.json(projectType);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching project type" });
      }
    })
    .post("/project-types", async (req, res) => {
      try {
        const validatedData = insertProjectTypeSchema.parse(req.body);
        const projectType = await storage.createProjectType(validatedData);
        res.status(201).json(projectType);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while creating project type" });
        }
      }
    })
    .put("/project-types/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const validatedData = insertProjectTypeSchema.partial().parse(req.body);
        const projectType = await storage.updateProjectType(id, validatedData);
        
        if (!projectType) {
          return res.status(404).json({ message: "Project type not found" });
        }
        
        res.json(projectType);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while updating project type" });
        }
      }
    })
    .delete("/project-types/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const deleted = await storage.deleteProjectType(id);
        
        if (!deleted) {
          return res.status(404).json({ message: "Project type not found" });
        }
        
        res.status(204).send();
      } catch (error) {
        res.status(500).json({ message: "An error occurred while deleting project type" });
      }
    });
  
  // Legal Statuses
  apiRouter
    .get("/legal-statuses", async (req, res) => {
      try {
        const legalStatuses = await storage.getAllLegalStatuses();
        res.json(legalStatuses);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching legal statuses" });
      }
    })
    .get("/legal-statuses/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const legalStatus = await storage.getLegalStatus(id);
        
        if (!legalStatus) {
          return res.status(404).json({ message: "Legal status not found" });
        }
        
        res.json(legalStatus);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching legal status" });
      }
    })
    .post("/legal-statuses", async (req, res) => {
      try {
        const validatedData = insertLegalStatusSchema.parse(req.body);
        const legalStatus = await storage.createLegalStatus(validatedData);
        res.status(201).json(legalStatus);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while creating legal status" });
        }
      }
    })
    .put("/legal-statuses/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const validatedData = insertLegalStatusSchema.partial().parse(req.body);
        const legalStatus = await storage.updateLegalStatus(id, validatedData);
        
        if (!legalStatus) {
          return res.status(404).json({ message: "Legal status not found" });
        }
        
        res.json(legalStatus);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while updating legal status" });
        }
      }
    })
    .delete("/legal-statuses/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const deleted = await storage.deleteLegalStatus(id);
        
        if (!deleted) {
          return res.status(404).json({ message: "Legal status not found" });
        }
        
        res.status(204).send();
      } catch (error) {
        res.status(500).json({ message: "An error occurred while deleting legal status" });
      }
    });
  
  // Centers
  apiRouter
    .get("/centers", async (req, res) => {
      try {
        const centers = await storage.getAllCenters();
        res.json(centers);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching centers" });
      }
    })
    .get("/centers/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const center = await storage.getCenter(id);
        
        if (!center) {
          return res.status(404).json({ message: "Center not found" });
        }
        
        res.json(center);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching center" });
      }
    })
    .post("/centers", async (req, res) => {
      try {
        const validatedData = insertCenterSchema.parse(req.body);
        const center = await storage.createCenter(validatedData);
        res.status(201).json(center);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while creating center" });
        }
      }
    })
    .put("/centers/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const validatedData = insertCenterSchema.partial().parse(req.body);
        const center = await storage.updateCenter(id, validatedData);
        
        if (!center) {
          return res.status(404).json({ message: "Center not found" });
        }
        
        res.json(center);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while updating center" });
        }
      }
    })
    .delete("/centers/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const deleted = await storage.deleteCenter(id);
        
        if (!deleted) {
          return res.status(404).json({ message: "Center not found" });
        }
        
        res.status(204).send();
      } catch (error) {
        res.status(500).json({ message: "An error occurred while deleting center" });
      }
    });
  
  // Center Services
  apiRouter
    .get("/centers/:centerId/services", async (req, res) => {
      try {
        const centerId = parseInt(req.params.centerId);
        const services = await storage.getCenterServices(centerId);
        res.json(services);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching center services" });
      }
    })
    .get("/center-services/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const service = await storage.getCenterService(id);
        
        if (!service) {
          return res.status(404).json({ message: "Center service not found" });
        }
        
        res.json(service);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching center service" });
      }
    })
    .post("/center-services", async (req, res) => {
      try {
        const validatedData = insertCenterServiceSchema.parse(req.body);
        const service = await storage.createCenterService(validatedData);
        res.status(201).json(service);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while creating center service" });
        }
      }
    })
    .put("/center-services/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const validatedData = insertCenterServiceSchema.partial().parse(req.body);
        const service = await storage.updateCenterService(id, validatedData);
        
        if (!service) {
          return res.status(404).json({ message: "Center service not found" });
        }
        
        res.json(service);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while updating center service" });
        }
      }
    })
    .delete("/center-services/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const deleted = await storage.deleteCenterService(id);
        
        if (!deleted) {
          return res.status(404).json({ message: "Center service not found" });
        }
        
        res.status(204).send();
      } catch (error) {
        res.status(500).json({ message: "An error occurred while deleting center service" });
      }
    });
  
  // Mail Offers
  apiRouter
    .get("/mail-offers", async (req, res) => {
      try {
        const mailOffers = await storage.getAllMailOffers();
        res.json(mailOffers);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching mail offers" });
      }
    })
    .get("/mail-offers/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const mailOffer = await storage.getMailOffer(id);
        
        if (!mailOffer) {
          return res.status(404).json({ message: "Mail offer not found" });
        }
        
        res.json(mailOffer);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching mail offer" });
      }
    })
    .post("/mail-offers", async (req, res) => {
      try {
        const validatedData = insertMailOfferSchema.parse(req.body);
        const mailOffer = await storage.createMailOffer(validatedData);
        res.status(201).json(mailOffer);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while creating mail offer" });
        }
      }
    })
    .put("/mail-offers/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const validatedData = insertMailOfferSchema.partial().parse(req.body);
        const mailOffer = await storage.updateMailOffer(id, validatedData);
        
        if (!mailOffer) {
          return res.status(404).json({ message: "Mail offer not found" });
        }
        
        res.json(mailOffer);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while updating mail offer" });
        }
      }
    })
    .delete("/mail-offers/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const deleted = await storage.deleteMailOffer(id);
        
        if (!deleted) {
          return res.status(404).json({ message: "Mail offer not found" });
        }
        
        res.status(204).send();
      } catch (error) {
        res.status(500).json({ message: "An error occurred while deleting mail offer" });
      }
    });
  
  // Center Mail Offers (Relations entre centres et services annexes)
  apiRouter
    .get("/centers/:centerId/mail-offers", async (req, res) => {
      try {
        const centerId = parseInt(req.params.centerId);
        const centerMailOffers = await storage.getCenterMailOffers(centerId);
        res.json(centerMailOffers);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching center mail offers" });
      }
    })
    .get("/centers/:centerId/available-mail-offers", async (req, res) => {
      try {
        const centerId = parseInt(req.params.centerId);
        const availableMailOffers = await storage.getCenterAvailableMailOffers(centerId);
        res.json(availableMailOffers);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching available mail offers" });
      }
    })
    .put("/centers/:centerId/mail-offers/:mailOfferId", async (req, res) => {
      try {
        const centerId = parseInt(req.params.centerId);
        const mailOfferId = parseInt(req.params.mailOfferId);
        
        // Validate the request body
        const schema = z.object({
          isAvailable: z.boolean()
        });
        
        const result = schema.safeParse(req.body);
        
        if (!result.success) {
          const validationError = fromZodError(result.error);
          return res.status(400).json({ message: validationError.message });
        }
        
        const updatedCenterMailOffer = await storage.updateCenterMailOfferAvailability(
          centerId, 
          mailOfferId, 
          result.data.isAvailable
        );
        
        res.json(updatedCenterMailOffer);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while updating mail offer availability" });
      }
    });
  
  // Projects
  apiRouter
    .get("/projects", async (req, res) => {
      try {
        const projects = await storage.getAllProjects();
        res.json(projects);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching projects" });
      }
    })
    .get("/projects/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const project = await storage.getProject(id);
        
        if (!project) {
          return res.status(404).json({ message: "Project not found" });
        }
        
        res.json(project);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching project" });
      }
    })
    .post("/projects", async (req, res) => {
      try {
        const validatedData = insertProjectSchema.parse(req.body);
        const project = await storage.createProject(validatedData);
        res.status(201).json(project);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while creating project" });
        }
      }
    })
    .put("/projects/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const validatedData = insertProjectSchema.partial().parse(req.body);
        const project = await storage.updateProject(id, validatedData);
        
        if (!project) {
          return res.status(404).json({ message: "Project not found" });
        }
        
        res.json(project);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while updating project" });
        }
      }
    })
    .delete("/projects/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const deleted = await storage.deleteProject(id);
        
        if (!deleted) {
          return res.status(404).json({ message: "Project not found" });
        }
        
        res.status(204).send();
      } catch (error) {
        res.status(500).json({ message: "An error occurred while deleting project" });
      }
    });
  
  // Company Config
  apiRouter
    .get("/company-config", async (req, res) => {
      try {
        const config = await storage.getCompanyConfig();
        
        if (!config) {
          return res.status(404).json({ message: "Company config not found" });
        }
        
        res.json(config);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching company config" });
      }
    })
    .put("/company-config", async (req, res) => {
      try {
        const validatedData = insertCompanyConfigSchema.parse(req.body);
        const config = await storage.updateCompanyConfig(validatedData);
        res.json(config);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while updating company config" });
        }
      }
    });
  
  // Authentication
  apiRouter
    .post("/auth/login", async (req, res) => {
      try {
        const { username, password } = req.body;
        
        if (!username || !password) {
          return res.status(400).json({ message: "Username and password are required" });
        }
        
        const user = await storage.getUserByUsername(username);
        
        if (!user || user.password !== password) {
          return res.status(401).json({ message: "Invalid credentials" });
        }
        
        // Send user without password
        const { password: _, ...userWithoutPassword } = user;
        res.json(userWithoutPassword);
      } catch (error) {
        res.status(500).json({ message: "An error occurred during login" });
      }
    })
    .post("/auth/register", async (req, res) => {
      try {
        const validatedData = insertUserSchema.parse(req.body);
        
        // Check if username exists
        const existingUser = await storage.getUserByUsername(validatedData.username);
        if (existingUser) {
          return res.status(409).json({ message: "Username already exists" });
        }
        
        const user = await storage.createUser(validatedData);
        
        // Send user without password
        const { password: _, ...userWithoutPassword } = user;
        res.status(201).json(userWithoutPassword);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred during registration" });
        }
      }
    });

  // Translations
  apiRouter
    .get("/translations", async (req, res) => {
      try {
        let translations;
        if (req.query.language) {
          translations = await storage.getTranslationsByLanguage(req.query.language as string);
        } else if (req.query.category) {
          translations = await storage.getTranslationsByCategory(req.query.category as string);
        } else {
          translations = await storage.getAllTranslations();
        }
        res.json(translations);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching translations" });
      }
    })
    .get("/translations/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const translation = await storage.getTranslation(id);
        
        if (!translation) {
          return res.status(404).json({ message: "Translation not found" });
        }
        
        res.json(translation);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching translation" });
      }
    })
    .get("/translations/key/:key", async (req, res) => {
      try {
        const key = req.params.key;
        const language = req.query.language as string || "fr";
        const translation = await storage.getTranslationByKey(key, language);
        
        if (!translation) {
          return res.status(404).json({ message: "Translation not found" });
        }
        
        res.json(translation);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while fetching translation" });
      }
    })
    .post("/translations", async (req, res) => {
      try {
        const validatedData = insertTranslationSchema.parse(req.body);
        const translation = await storage.createTranslation(validatedData);
        res.status(201).json(translation);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while creating translation" });
        }
      }
    })
    .put("/translations/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const validatedData = insertTranslationSchema.partial().parse(req.body);
        const translation = await storage.updateTranslation(id, validatedData);
        
        if (!translation) {
          return res.status(404).json({ message: "Translation not found" });
        }
        
        res.json(translation);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const validationError = fromZodError(error);
          res.status(400).json({ message: validationError.message });
        } else {
          res.status(500).json({ message: "An error occurred while updating translation" });
        }
      }
    })
    .post("/translations/upsert", async (req, res) => {
      try {
        const { key, language, value, category } = req.body;
        
        if (!key || !language || !value) {
          return res.status(400).json({ message: "Key, language, and value are required" });
        }
        
        const translation = await storage.upsertTranslation(key, language, value, category);
        res.status(201).json(translation);
      } catch (error) {
        res.status(500).json({ message: "An error occurred while upserting translation" });
      }
    })
    .delete("/translations/:id", async (req, res) => {
      try {
        const id = parseInt(req.params.id);
        const deleted = await storage.deleteTranslation(id);
        
        if (!deleted) {
          return res.status(404).json({ message: "Translation not found" });
        }
        
        res.status(204).send();
      } catch (error) {
        res.status(500).json({ message: "An error occurred while deleting translation" });
      }
    });

  // Configuration de l'authentification Azure AD
  await setupAuth(app);

  // Mount the API router
  app.use('/api', apiRouter);

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