import type { Express, RequestHandler } from "express";
import session from "express-session";
import connectPg from "connect-pg-simple";

// Hardcoded credentials
const CREDENTIALS = {
  admin: { password: "1234", role: "admin", firstName: "Admin", lastName: "User" },
  superadmin: { password: "1234", role: "superadmin", firstName: "Super", lastName: "Admin" }
};

export function getSession() {
  const sessionTtl = 7 * 24 * 60 * 60 * 1000; // 1 week
  const pgStore = connectPg(session);
  const sessionStore = new pgStore({
    conString: process.env.DATABASE_URL,
    createTableIfMissing: false,
    ttl: sessionTtl,
    tableName: "sessions",
  });
  return session({
    secret: process.env.SESSION_SECRET!,
    store: sessionStore,
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      secure: false, // Changed to false for development
      maxAge: sessionTtl,
    },
  });
}

export async function setupAuth(app: Express) {
  app.set("trust proxy", 1);
  app.use(getSession());

  // Login route
  app.post("/api/login", (req, res) => {
    const { username, password } = req.body;
    
    if (!username || !password) {
      return res.status(400).json({ message: "Username and password required" });
    }

    const user = CREDENTIALS[username as keyof typeof CREDENTIALS];
    if (!user || user.password !== password) {
      return res.status(401).json({ message: "Invalid credentials" });
    }

    // Set session
    (req.session as any).user = {
      id: username,
      email: `${username}@sapiens.com`,
      firstName: user.firstName,
      lastName: user.lastName,
      role: user.role,
      isAuthenticated: true
    };

    res.json({
      id: username,
      email: `${username}@sapiens.com`,
      firstName: user.firstName,
      lastName: user.lastName,
      role: user.role
    });
  });

  // Logout route
  app.post("/api/logout", (req, res) => {
    req.session.destroy((err) => {
      if (err) {
        return res.status(500).json({ message: "Could not log out" });
      }
      res.json({ message: "Logged out successfully" });
    });
  });
}

export const isAuthenticated: RequestHandler = (req, res, next) => {
  const user = (req.session as any)?.user;
  
  if (!user || !user.isAuthenticated) {
    return res.status(401).json({ message: "Unauthorized" });
  }

  req.user = user;
  next();
};