import frappe
from frappe.model.document import Document
from .db_service import DbService

class ContactService:
    
    @staticmethod
    def create(data: dict) -> Document:
        """Create a new contact."""
        print("DEBUG: Creating new Contact with data:", data)
        contact = frappe.get_doc({
            "doctype": "Contact",
            **data
        })
        contact.insert(ignore_permissions=True)
        print("DEBUG: Created new Contact:", contact.as_dict())
        return contact

    @staticmethod
    def link_contact_to_customer(contact_doc: Document, customer_type: str, customer_name: str):
        """Link a contact to a customer or lead."""
        print(f"DEBUG: Linking Contact {contact_doc.name} to {customer_type} {customer_name}")
        contact_doc.customer_type = customer_type
        contact_doc.customer_name = customer_name
        contact_doc.append("links", {
            "link_doctype": customer_type,
            "link_name": customer_name
        })
        contact_doc.save(ignore_permissions=True)
        print(f"DEBUG: Linked Contact {contact_doc.name} to {customer_type} {customer_name}")
        
    @staticmethod
    def link_contact_to_address(contact_doc: Document, address_name: str):
        """Link an address to a contact."""
        print(f"DEBUG: Linking Address {address_name} to Contact {contact_doc.name}")
        contact_doc.append("addresses", {
            "address": address_name
        })
        contact_doc.append("links", {
            "link_doctype": "Address",
            "link_name": address_name
        })
        contact_doc.save(ignore_permissions=True)
        print(f"DEBUG: Linked Address {address_name} to Contact {contact_doc.name}")
        
    @staticmethod
    def get_or_throw(contact_name: str) -> Document:
        """Retrieve a Contact document or throw an error if it does not exist."""
        return DbService.get_or_throw("Contact", contact_name)