import json

class DocumentRepository:
    def __init__(self, connection):
        self.conn = connection

    def insert(self, data: dict):
        query = """
        INSERT INTO PATIENT_DOCUMENT (
            TENANT_NAME, CLINIC_ID, PATIENT_ID,
            BUCKET_NAME, S3_KEY,
            DOCUMENT_TYPE, DOCUMENT_FORMAT,
            FILE_NAME_ORIGINAL, CONTENT_TYPE,
            FILE_SIZE_BYTES, REVIEW_STATUS,
            CUSTOM_METADATA
        )
        VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
        """

        custom_metadata_json = None
        if data.get("custom_metadata"):
            custom_metadata_json = json.dumps(data["custom_metadata"])

        values = (
            data["tenant_name"],
            data["clinic_id"],
            data["patient_id"],
            data["bucket"],
            data["key"],
            data["document_type"],
            data["document_format"],
            data["file_name"],
            data["content_type"],
            data.get("size"),
            data.get("review_status"),
            custom_metadata_json,
        )

        cursor = self.conn.cursor()
        cursor.execute(query, values)
        self.conn.commit()

    def get_by_key(self, bucket, key):
        query = """
        SELECT * FROM PATIENT_DOCUMENT
        WHERE BUCKET_NAME=%s AND S3_KEY=%s AND IS_DELETED=0
        """
        cursor = self.conn.cursor(dictionary=True)
        cursor.execute(query, (bucket, key))
        return cursor.fetchone()

    def soft_delete(self, bucket, key):
        query = """
        UPDATE PATIENT_DOCUMENT
        SET IS_DELETED=1, DELETED_AT=NOW()
        WHERE BUCKET_NAME=%s AND S3_KEY=%s
        """
        cursor = self.conn.cursor()
        cursor.execute(query, (bucket, key))
        self.conn.commit()

    def list_documents(self, tenant_name, patient_id=None):
        query = """
        SELECT * FROM PATIENT_DOCUMENT
        WHERE TENANT_NAME=%s AND IS_DELETED=0
        """
        values = [tenant_name]
        
        if patient_id is not None:
            query += " AND PATIENT_ID=%s"
            values.append(patient_id)
            
        cursor = self.conn.cursor(dictionary=True)
        cursor.execute(query, tuple(values))
        return cursor.fetchall()