import type { Express } from "express";
import { z } from "zod";
import {
  insertUserSchema,
  insertFormSchema,
  DEPARTMENTS,
  DEPARTMENT_ORDER,
  DEPARTMENT_NAMES,
} from "../shared/schema.js";
import { LocalStorage } from "./storage.js";

declare global {
  namespace Express {
    interface Request {
      currentUser?: any;
    }
  }
}

// Initialize local storage (will be set in registerLocalRoutes)
let storage: LocalStorage;

export function registerLocalRoutes(app: Express, db: any): void {
  // Initialize storage with database instance
  storage = new LocalStorage(db);
  
  // Auth routes
  app.get('/api/auth/user', (req: any, res) => {
    try {
      if (req.session?.user) {
        return res.json(req.session.user);
      }
      res.status(401).json({ message: "Unauthorized" });
    } catch (error) {
      console.error("Error fetching user:", error);
      res.status(500).json({ message: "Failed to fetch user" });
    }
  });

  // Traditional login for internal system
  app.post('/api/auth/login', async (req, res) => {
    try {
      const { username, password } = req.body;
      
      if (!username || !password) {
        return res.status(400).json({ message: 'نام کاربری و رمز عبور الزامی است' });
      }

      const user = await storage.verifyPassword(username, password);
      if (!user) {
        return res.status(401).json({ message: 'نام کاربری یا رمز عبور اشتباه است' });
      }

      if (!user.isActive) {
        return res.status(401).json({ message: 'حساب کاربری غیرفعال است' });
      }

      // Parse departmentAccess properly before storing in session
      let parsedDepartmentAccess = [];
      if (user.departmentAccess) {
        if (typeof user.departmentAccess === 'string') {
          try {
            parsedDepartmentAccess = JSON.parse(user.departmentAccess);
          } catch (e) {
            console.error('Error parsing departmentAccess:', e);
            parsedDepartmentAccess = [];
          }
        } else if (Array.isArray(user.departmentAccess)) {
          parsedDepartmentAccess = user.departmentAccess;
        }
      }

      // Set user session and save
      (req as any).session.user = {
        id: user.id,
        username: user.username,
        fullName: user.fullName,
        department: user.department,
        position: user.position,
        isActive: user.isActive,
        signatureImageUrl: user.signatureImageUrl,
        departmentAccess: parsedDepartmentAccess
      };
      
      // Force session save
      (req as any).session.save((err: any) => {
        if (err) {
          console.error("Session save error:", err);
        } else {
          console.log("Session saved successfully for user:", user.username);
        }
      });
      
      console.log("User login successful:", { 
        username: user.username, 
        department: user.department, 
        position: user.position,
        hasSignature: !!user.signatureImageUrl 
      });
      
      res.json({ 
        user: {
          id: user.id,
          username: user.username,
          fullName: user.fullName,
          department: user.department,
          position: user.position,
          isActive: user.isActive,
          signatureImageUrl: user.signatureImageUrl
        }
      });
    } catch (error) {
      console.error("Login error:", error);
      res.status(500).json({ message: "خطا در ورود به سیستم" });
    }
  });

  // Logout endpoint
  app.post('/api/auth/logout', (req: any, res) => {
    try {
      console.log("Logout request received");
      
      // Always respond with success, even if no session exists
      if (req.session) {
        req.session.destroy((err: any) => {
          if (err) {
            console.error("Error destroying session:", err);
            // Still return success to avoid frontend hanging
          }
          res.clearCookie('connect.sid', { 
            path: '/',
            httpOnly: true,
            secure: false // Set to true in production with HTTPS
          });
          console.log("Session destroyed successfully");
          res.json({ message: 'با موفقیت خارج شدید' });
        });
      } else {
        console.log("No active session found, responding with success");
        res.clearCookie('connect.sid', { 
          path: '/',
          httpOnly: true,
          secure: false
        });
        res.json({ message: 'با موفقیت خارج شدید' });
      }
    } catch (error) {
      console.error("Logout error:", error);
      // Always return success to prevent frontend hanging
      res.clearCookie('connect.sid', { 
        path: '/',
        httpOnly: true,
        secure: false
      });
      res.json({ message: 'با موفقیت خارج شدید' });
    }
  });

  // Middleware to check internal authentication
  const requireAuth = (req: any, res: any, next: any) => {
	  const u = req.session?.user;
	  console.log("Auth check - Session ID:", req.sessionID, " user:", u?.username);
	  if (!u) return res.status(401).json({ message: "لطفا وارد سیستم شوید" });
	  req.currentUser = u; // <-- همین خط مشکل را حل می‌کند
	  next();
};

  // Dashboard stats
  app.get('/api/dashboard/stats', requireAuth, async (req: any, res) => {
    try {
      const stats = await storage.getDashboardStats();
      res.json(stats);
    } catch (error) {
      console.error("Error fetching dashboard stats:", error);
      res.status(500).json({ message: "خطا در دریافت آمار داشبورد" });
    }
  });

  // Forms endpoints
  app.get('/api/forms', requireAuth, async (req: any, res) => {
    try {
      const user = req.session.user;
      let forms = await storage.getAllForms();
      
      // Filter forms based on user access
      if (user.department !== 'admin') {
        const userDepartments = [user.department, ...(user.departmentAccess || [])];
        forms = forms.filter((form: any) => 
          userDepartments.includes(form.currentDepartment) || 
          form.createdBy === user.id
        );
      }
      
      res.json(forms);
    } catch (error) {
      console.error("Error fetching forms:", error);
      res.status(500).json({ message: "خطا در دریافت فرم‌ها" });
    }
  });

  app.post('/api/forms', requireAuth, async (req, res) => {
    try {
      const user = (req as any).session.user;
      
      console.log("Creating form with user:", user);
      console.log("Request body:", req.body);
      
      // Generate unique form number with timestamp
      const now = new Date();
      const timestamp = Date.now();
      const formNumber = `F${String(timestamp).slice(-6)}`;
      
      const formData = {
        ...req.body,
        formNumber,
        currentDepartment: 'engineering',
        status: 'pending',
        createdBy: user.id,
        creatorName: user.fullName || user.username,
      };
      
      console.log("Form data to create:", formData);
      
      // Create form without schema validation first (will validate in storage)
      const form = await storage.createForm(formData);
      
      console.log("Created form:", form);
      res.status(201).json(form);
    } catch (error: any) {
      console.error("Error creating form:", error);
      console.error("Error stack:", error?.stack);
      res.status(500).json({ 
        message: "خطا در ایجاد فرم", 
        error: error?.message || String(error),
        details: error?.stack
      });
    }
  });

app.post("/api/forms/:id/apply-signature", requireAuth, async (req: any, res: any) => {
  try {
    const formId = req.params.id as string;
    const user = req.session?.user as { id: string; username?: string; fullName?: string; signatureImageUrl?: string } | undefined;
    const { fieldName, signatureText, signatureImageUrl } = (req.body || {}) as {
      fieldName?: string;
      signatureText?: string;
      signatureImageUrl?: string;
    };

    if (!formId) return res.status(400).json({ message: "formId لازم است" });
    if (!fieldName) return res.status(400).json({ message: "fieldName لازم است" });
    if (!user?.id) return res.status(401).json({ message: "Unauthorized" });

    // اگر تصویر جدید آمد، هم در DB ذخیره کن هم سشن را بروز کن
    let finalImage = (signatureImageUrl ?? "").trim() || "";
    if (finalImage) {
      await storage.updateUserSignature(user.id, finalImage);
      // سشن را هم به‌روز کن تا فرانت بلافاصله ببیند
      req.session.user.signatureImageUrl = finalImage;
      req.session.save(() => {});
    } else {
      // اگر کلاینت چیزی نفرستاد، از تصویر ذخیره‌شده‌ی کاربر استفاده کن
      finalImage = user.signatureImageUrl || "";
      if (!finalImage) {
        const fresh = await storage.getUserById(user.id);
        finalImage = fresh?.signatureImageUrl || "";
      }
    }

    await storage.applyDigitalSignature(formId, fieldName, {
      userId: user.id,
      username: user.username ?? null,
      fullName: user.fullName ?? null,
      signatureText: signatureText ?? null,
      signatureImageUrl: finalImage || null, // اینجا حتماً ایمیج می‌فرستیم اگر موجود باشد
    });

    return res.status(200).json({ ok: true });
  } catch (e) {
    console.error("[apply-signature] error:", e);
    return res.status(500).json({ message: "Failed to apply signature" });
  }
});
 
app.get('/api/forms/:id', requireAuth, async (req, res) => {
    try {
      const form = await storage.getForm(req.params.id);
      if (!form) {
        return res.status(404).json({ message: "فرم یافت نشد" });
      }
      res.json(form);
    } catch (error) {
      console.error("Error fetching form:", error);
      res.status(500).json({ message: "خطا در دریافت فرم" });
    }
  });

  app.put('/api/forms/:id', requireAuth, async (req, res) => {
    try {
      const updates = req.body;
      const form = await storage.updateForm(req.params.id, updates);
      res.json(form);
    } catch (error) {
      console.error("Error updating form:", error);
      res.status(500).json({ message: "خطا در به‌روزرسانی فرم" });
    }
  });

  // Users endpoints  
  app.get('/api/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: "خطا در دریافت کاربران" });
    }
  });

  // Update user (admin only)
  app.put('/api/users/:id', requireAuth, async (req, res) => {
    try {
      const { id } = req.params;
      const updates = req.body;
      
      console.log("Updating user:", id, "with data:", updates);
      
      // Validate the update data
      const validatedUpdates = insertUserSchema.partial().parse(updates);
      
      const updatedUser = await storage.updateUser(id, validatedUpdates);
      
      console.log("User updated successfully:", updatedUser);
      res.json(updatedUser);
    } catch (error) {
      console.error("Error updating user:", error);
      res.status(500).json({ message: "خطا در بروزرسانی کاربر" });
    }
  });

  // Delete user (admin only)
  app.delete('/api/users/:id', requireAuth, async (req, res) => {
    try {
      const { id } = req.params;
      
      console.log("Deleting user:", id);
      
      await storage.deleteUser(id);
      
      console.log("User deleted successfully:", id);
      res.json({ message: "کاربر با موفقیت حذف شد" });
    } catch (error) {
      console.error("Error deleting user:", error);
      res.status(500).json({ message: "خطا در حذف کاربر" });
    }
  });

  app.get('/api/users/department/:department', requireAuth, async (req, res) => {
    try {
      const users = await storage.getUsersByDepartment(req.params.department);
      res.json(users);
    } catch (error) {
      console.error("Error fetching users by department:", error);
      res.status(500).json({ message: "خطا در دریافت کاربران بخش" });
    }
  });

  // Archive endpoints
  app.get('/api/forms/archived', requireAuth, async (req, res) => {
    try {
      const archivedForms = await storage.getArchivedForms();
      res.json(archivedForms);
    } catch (error) {
      console.error("Error fetching archived forms:", error);
      res.status(500).json({ message: "خطا در دریافت فرم‌های بایگانی شده" });
    }
  });

  // Health check
  app.get('/api/health', (req, res) => {
    res.json({ 
      status: 'OK', 
      timestamp: new Date().toISOString(),
      environment: process.env.NODE_ENV,
      port: process.env.PORT 
    });
  });

  console.log("✅ Local API routes registered successfully");
}