import requests
import mysql.connector
import sys

API_URL = "https://partner-api.monta.com/api/v1/subscriptions"
API_KEY = "f2819009-a0e5-4bc1-bc40-2dfeebb8a4c3"  # Insert your Monta Partner API key/token here

DB_CONFIG = {
    "host": "chge.at",
    "user": "monta_test_db_user",
    "password": "Ycze9_733",
    "database": "monta_test_db",
}

def fetch_subscriptions(page=0, per_page=100):
    headers = {
        "accept": "application/json",
        "Authorization": f"Bearer {API_KEY}"
    }
    params = {"page": page, "perPage": per_page}
    resp = requests.get(API_URL, headers=headers, params=params)
    resp.raise_for_status()
    return resp.json()

def get_field(obj, field, default=None):
    # Helper: safely extract a value or return None/default
    return obj[field] if field in obj else default

def insert_update_subscription(cursor, sub, event_time):

    """Inserts or updates a subscription record in the database."""
    sql = """
    INSERT INTO subscriptions (
        id, state, nextPurchaseAt, cancelledAt, endAt, customerId,
        customerType, planId, createdAt, updatedAt, deletedAt, last_event_time
    ) VALUES (
        %(id)s, %(state)s, %(nextPurchaseAt)s, %(cancelledAt)s, %(endAt)s, %(customerId)s,
        %(customerType)s, %(planId)s, %(createdAt)s, %(updatedAt)s, %(deletedAt)s, %(last_event_time)s
    )
    ON DUPLICATE KEY UPDATE
        state = VALUES(state), nextPurchaseAt = VALUES(nextPurchaseAt), cancelledAt = VALUES(cancelledAt),
        endAt = VALUES(endAt), customerId = VALUES(customerId), customerType = VALUES(customerType),
        planId = VALUES(planId), createdAt = VALUES(createdAt), updatedAt = VALUES(updatedAt), deletedAt = VALUES(deletedAt),
        last_event_time = VALUES(last_event_time)
    """

    data = {
        'id': get_field(sub, 'id'),
        'state': get_field(sub, 'state'),
        'nextPurchaseAt': get_field(sub, 'nextPurchaseAt'),
        'cancelledAt': get_field(sub, 'cancelledAt'),
        'endAt': get_field(sub, 'endAt'),
        'customerId': get_field(sub, 'customerId'),
        'customerType': get_field(sub, 'customerType'),
        'planId': get_field(sub, 'planId'),
        'createdAt': get_field(sub, 'createdAt'),
        'updatedAt': get_field(sub, 'updatedAt'),
        'deletedAt': get_field(sub, 'deletedAt'),
        'last_event_time': event_time
    }
    cursor.execute(sql, data)
    print(f"Inserted subscription ID: {data['id']}")

def main():
    # Connect to MySQL
    cnx = mysql.connector.connect(**DB_CONFIG)
    cursor = cnx.cursor()
    page, total = 0, 0
    per_page = 100
    while True:
        result = fetch_subscriptions(page=page, per_page=per_page)
        subs = result.get('data', []) or result.get('subscriptions', [])
        if not subs:
            break
        for sub in subs:
            # Use the most up-to-date timestamp available as 'last_event_time'
            event_time = (get_field(sub, 'updatedAt') or
                          get_field(sub, 'createdAt') or
                          None)
            insert_update_subscription(cursor, sub, event_time)
        cnx.commit()
        total += len(subs)
        print(f"Imported {total} subscriptions...")
        # Pagination: Stop if we've reached the last page
        if len(subs) < per_page:
            break
        page += 1
    cursor.close()
    cnx.close()
    print("Done.")

if __name__ == "__main__":
    main()
