import {
  createTeamMemberSchema,
  updateTeamMemberSchema,
  normalizeTeamMemberPayload,
} from "../models/teamMember.schema.js";
import {
  listTeamMembers,
  getTeamMemberById,
  createTeamMember,
  updateTeamMember,
  deleteTeamMember,
} from "../services/teamMember.service.js";
import { successResponse, errorResponse } from "../utils/response.js";
import { HTTP_STATUS } from "../constants/index.js";
import logger from "../utils/logger.js";

export const list = async (req, res, next) => {
  try {
    const filters = {};
    
    // Optional query parameters
    if (req.query.category) {
      filters.category = req.query.category;
    }
    if (req.query.status) {
      filters.status = req.query.status;
    }
    // If no status filter, show all (both Active and Inactive)
    // The service will handle this

    const items = await listTeamMembers(filters);
    return successResponse(res, items, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error listing team members:", err);
    next(err);
  }
};

export const getById = async (req, res, next) => {
  try {
    const { id } = req.params;
    if (!id) {
      return errorResponse(res, "Team Member ID is required", HTTP_STATUS.BAD_REQUEST);
    }
    const item = await getTeamMemberById(id);
    if (!item) {
      return errorResponse(res, "Team member not found", HTTP_STATUS.NOT_FOUND);
    }
    return successResponse(res, item, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error getting team member:", err);
    next(err);
  }
};

export const create = async (req, res, next) => {
  try {
    const normalized = normalizeTeamMemberPayload(req.body);
    const parsed = createTeamMemberSchema.safeParse(normalized);
    if (!parsed.success) {
      return errorResponse(
        res,
        "Validation failed",
        HTTP_STATUS.BAD_REQUEST,
        parsed.error.flatten()
      );
    }
    const created = await createTeamMember(parsed.data);
    logger.info(`Team member created with ID: ${created._id || created.id}`);
    return successResponse(res, created, HTTP_STATUS.CREATED);
  } catch (err) {
    logger.error("Error creating team member:", err);
    next(err);
  }
};

export const update = async (req, res, next) => {
  try {
    const { id } = req.params;
    if (!id) {
      return errorResponse(res, "Team Member ID is required", HTTP_STATUS.BAD_REQUEST);
    }
    const normalized = normalizeTeamMemberPayload(req.body);
    const parsed = updateTeamMemberSchema.safeParse(normalized);
    if (!parsed.success) {
      return errorResponse(
        res,
        "Validation failed",
        HTTP_STATUS.BAD_REQUEST,
        parsed.error.flatten()
      );
    }
    const updated = await updateTeamMember(id, parsed.data);
    return successResponse(res, updated, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error updating team member:", err);
    if (err.message === "Team member not found") {
      return errorResponse(res, err.message, HTTP_STATUS.NOT_FOUND);
    }
    next(err);
  }
};

export const remove = async (req, res, next) => {
  try {
    const { id } = req.params;
    if (!id) {
      return errorResponse(res, "Team Member ID is required", HTTP_STATUS.BAD_REQUEST);
    }
    const deleted = await deleteTeamMember(id);
    if (!deleted) {
      return errorResponse(res, "Team member not found", HTTP_STATUS.NOT_FOUND);
    }
    return successResponse(res, { message: "Team member deleted successfully" }, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error deleting team member:", err);
    next(err);
  }
};

// Seed hardcoded team members
export const seed = async (req, res, next) => {
  try {
    const { TeamMemberModel } = await import("../models/teamMember.model.js");
    
    const hardcodedMembers = [
      // Leadership Team
      { name: "Naseer Akhtar", role: "Founder & COO (25+ Years)", phd: "Leadership & Strategy", img: "/LeaderShip/Naseer.jpg", category: "Leadership", order: 0, status: "Active" },
      { name: "Dr. Ziad Nayyer", role: "Chief Technology Officer (16+ Years)", phd: "Technology & Innovation", img: "/LeaderShip/ZiadNayyer.jpg", category: "Leadership", order: 1, status: "Active" },
      { name: "Dr. Faheem", role: "Web Data Engineer (8+ Years)", phd: "Operations & Management", img: "/LeaderShip/Faheem.jpg", category: "Leadership", order: 2, status: "Active" },
      { name: "Zaheer Ahmad", role: "Chief Solutions Architect (25+ Years)", phd: "Finance & Economics", img: "/LeaderShip/zaheer.png", category: "Leadership", order: 3, status: "Active" },
      // Core Team
      { name: "Muhammad Waseem", role: "Senior Software Engineer (2+ Years)", phd: "Full Stack Development", img: "/team/MuhammadWaseem.jpg", category: "Core Team", order: 0, status: "Active" },
      { name: "Fiza Khan", role: "I.T Staff Augmentation (8+ Years)", phd: "Product Design & Research", img: "/team/MissFizza.jpg", category: "Core Team", order: 1, status: "Active" },
      { name: "Umar Hayyat", role: "Digital Marketing and SEO (2+ Years)", phd: "System Architecture", img: "/team/MuhammadUmarHayaat.jpg", category: "Core Team", order: 2, status: "Active" },
      { name: "Usman Ali", role: "Custom Software Development (10+ Years)", phd: "Web Technologies", img: "/team/UsmanAli.jpg", category: "Core Team", order: 3, status: "Active" },
      { name: "Zuhaib Hussain", role: "AI Integration & Tools (4+ Years)", phd: "Cloud Infrastructure", img: "/team/ZuhaibHussainButt.jpg", category: "Core Team", order: 4, status: "Active" },
      { name: "Dr. Mohsin shamas", role: "Business and Finance (13+ Years)", phd: "iOS & Android Development", img: "/team/DrMohsin.jpg", category: "Core Team", order: 5, status: "Active" },
      { name: "Dr. Qamar Askari", role: "AI/ML Engineer (8+ Years)", phd: "Quality Assurance", img: "/team/Dr.QamarAskari.jpg", category: "Core Team", order: 6, status: "Active" },
      { name: "Ms. Isha Loak Choudhry", role: "UI/UX Designer (6+ Years)", phd: "Design & Research", img: "/team/IshaLoakChoudhry.jpg", category: "Core Team", order: 7, status: "Active" },
    ];

    const results = [];
    for (const member of hardcodedMembers) {
      // Check if member already exists (by name and category)
      const existing = await TeamMemberModel.findOne({ 
        name: member.name, 
        category: member.category 
      });
      
      if (existing) {
        // Update existing member
        const updated = await TeamMemberModel.findByIdAndUpdate(
          existing._id,
          { $set: member },
          { new: true }
        );
        results.push({ action: "updated", member: updated.name, id: updated._id });
      } else {
        // Create new member
        const created = await TeamMemberModel.create(member);
        results.push({ action: "created", member: created.name, id: created._id });
      }
    }

    logger.info(`Seeded ${results.length} team members`);
    return successResponse(res, { 
      message: "Team members seeded successfully",
      results 
    }, HTTP_STATUS.OK);
  } catch (err) {
    logger.error("Error seeding team members:", err);
    next(err);
  }
};
