import frappe, json
from custom_ui.db_utils import build_success_response, build_error_response
# ===============================================================================
# EMPLOYEE API METHODS
# ===============================================================================

@frappe.whitelist()
def get_employees(company: str, roles=[]):
    """Get a list of employees for a given company. Can be filtered by role."""
    roles = json.loads(roles) if isinstance(roles, str) else roles
    filters = {"company": company}
    if roles:
        filters["designation"] = ["in", roles]
    try:
        employee_names = frappe.get_all(
            "Employee",
            filters=filters,
            pluck="name"
        )
        employees = [frappe.get_doc("Employee", name).as_dict() for name in employee_names]
        return build_success_response(employees)
    except Exception as e:
        return build_error_response(str(e), 500)
    
@frappe.whitelist()
def get_employees_organized(company: str, roles=[]):
    """Get all employees for a company organized by designation."""
    roles = json.loads(roles) if isinstance(roles, str) else roles
    try:
        filters = {"company": company}
        if roles:
            filters["designation"] = ["in", roles]
        employee_names = frappe.get_all(
            "Employee",
            filters=filters,
            pluck="name"
        )
        employees = [frappe.get_doc("Employee", name).as_dict() for name in employee_names]
        
        organized = {}
        for emp in employees:
            designation = emp.get("designation", "Unassigned")
            if designation not in organized:
                organized[designation] = []
            organized[designation].append(emp)
        
        return build_success_response(organized)
    except Exception as e:
        return build_error_response(str(e), 500)