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, S3_VERSION_ID,
            DOCUMENT_TYPE, DOCUMENT_FORMAT, REVIEW_STATUS,
            FILE_NAME_ORIGINAL, FILE_NAME_SAFE, FILE_EXTENSION,
            CONTENT_TYPE, FILE_SIZE_BYTES, ETAG,
            CUSTOM_METADATA_JSON
        )
        VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
        """

        # Convert metadata to JSON
        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.get("version_id"),
            data["document_type"],
            data["document_format"],
            data.get("review_status"),
            data["file_name"],
            data["file_name_safe"],
            data.get("file_extension"),
            data["content_type"],
            data.get("size"),
            data.get("etag"),
            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, limit=100, offset=0):
        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)

        query += " ORDER BY CREATED_AT DESC LIMIT %s OFFSET %s"
        values.extend([limit, offset])

        cursor = self.conn.cursor(dictionary=True)
        cursor.execute(query, tuple(values))
        return cursor.fetchall()

    def document_exists(self, bucket, key):
        query = """
        SELECT 1
        FROM PATIENT_DOCUMENT
        WHERE BUCKET_NAME=%s
          AND S3_KEY=%s
          AND IS_DELETED=0
        LIMIT 1
        """
        cursor = self.conn.cursor()
        cursor.execute(query, (bucket, key))
        return cursor.fetchone() is not None