import { TeamMemberModel } from "../models/teamMember.model.js";
import logger from "../utils/logger.js";

export async function createTeamMember(data) {
  try {
    const created = await TeamMemberModel.create(data);
    logger.info(`Team member created with ID: ${created._id}`);
    return created;
  } catch (error) {
    logger.error("Error in createTeamMember service:", error);
    throw error;
  }
}

export async function listTeamMembers(filters = {}) {
  try {
    const query = {};
    
    if (filters.category) {
      query.category = filters.category;
    }
    
    // Only filter by status if explicitly provided
    // This allows admin panel to see all members (Active + Inactive)
    if (filters.status) {
      query.status = filters.status;
    }
    // If no status filter, return all members (both Active and Inactive)

    const items = await TeamMemberModel.find(query)
      .sort({ category: 1, order: 1, createdAt: -1 })
      .lean();
    return items;
  } catch (error) {
    logger.error("Error in listTeamMembers service:", error);
    throw error;
  }
}

export async function getTeamMemberById(id) {
  try {
    if (!id) {
      throw new Error("Team Member ID is required");
    }
    const item = await TeamMemberModel.findById(id).lean();
    return item || null;
  } catch (error) {
    logger.error("Error in getTeamMemberById service:", error);
    throw error;
  }
}

export async function updateTeamMember(id, data) {
  try {
    if (!id) {
      throw new Error("Team Member ID is required");
    }
    const updated = await TeamMemberModel.findByIdAndUpdate(
      id,
      { $set: data },
      { new: true, runValidators: true }
    ).lean();
    if (!updated) {
      throw new Error("Team member not found");
    }
    logger.info(`Team member updated with ID: ${id}`);
    return updated;
  } catch (error) {
    logger.error("Error in updateTeamMember service:", error);
    throw error;
  }
}

export async function deleteTeamMember(id) {
  try {
    if (!id) {
      throw new Error("Team Member ID is required");
    }
    const res = await TeamMemberModel.findByIdAndDelete(id).lean();
    return !!res;
  } catch (error) {
    logger.error("Error in deleteTeamMember service:", error);
    throw error;
  }
}

