import express from "express";
import { v4 as uuidv4 } from "uuid";

const router = express.Router();

// In-memory store (replace with database in production)
const profiles = new Map([
  [
    "1",
    {
      id: "1",
      name: "Pastor John",
      role: "admin",
      avatar: "👨‍💼",
      createdAt: new Date().toISOString(),
    },
  ],
  [
    "2",
    {
      id: "2",
      name: "Sarah Miller",
      role: "leader",
      avatar: "👩‍🎤",
      createdAt: new Date().toISOString(),
    },
  ],
  [
    "3",
    {
      id: "3",
      name: "Mike Johnson",
      role: "tech",
      avatar: "🎛️",
      createdAt: new Date().toISOString(),
    },
  ],
]);

// Get all profiles
router.get("/", (req, res) => {
  const result = Array.from(profiles.values());

  res.json({
    profiles: result,
    total: result.length,
  });
});

// Get single profile
router.get("/:id", (req, res) => {
  const profile = profiles.get(req.params.id);

  if (!profile) {
    return res.status(404).json({ error: "Profile not found" });
  }

  res.json({ profile });
});

// Create profile
router.post("/", (req, res) => {
  const { name, role, avatar } = req.body;

  if (!name) {
    return res.status(400).json({ error: "Name is required" });
  }

  const profile = {
    id: uuidv4(),
    name,
    role: role || "volunteer",
    avatar: avatar || "👤",
    createdAt: new Date().toISOString(),
  };

  profiles.set(profile.id, profile);

  res.status(201).json({
    message: "Profile created successfully",
    profile,
  });
});

// Update profile
router.put("/:id", (req, res) => {
  const profile = profiles.get(req.params.id);

  if (!profile) {
    return res.status(404).json({ error: "Profile not found" });
  }

  const { name, role, avatar } = req.body;

  const updatedProfile = {
    ...profile,
    name: name || profile.name,
    role: role || profile.role,
    avatar: avatar || profile.avatar,
  };

  profiles.set(profile.id, updatedProfile);

  res.json({
    message: "Profile updated successfully",
    profile: updatedProfile,
  });
});

// Delete profile
router.delete("/:id", (req, res) => {
  const profile = profiles.get(req.params.id);

  if (!profile) {
    return res.status(404).json({ error: "Profile not found" });
  }

  // Don't allow deleting admin profiles
  if (profile.role === "admin") {
    return res.status(403).json({ error: "Cannot delete admin profile" });
  }

  profiles.delete(req.params.id);

  res.json({ message: "Profile deleted successfully" });
});

export default router;
