from src.internals.database.database import cached_count, cached_query


def get_share(share_id: int, reload=False):
    key = f"share:{share_id}"
    query = """
        SELECT *
        FROM shares
        WHERE id = %s
    """
    return cached_query(query, key, (share_id,), reload=reload, single=True)


def get_shares(offset: int, limit: int = 50, reload=False):
    key = f"all_shares:{limit}:{offset}:"
    query = """
        SELECT *
        FROM shares
        ORDER BY id DESC
        OFFSET %s
        LIMIT %s
    """
    return cached_query(query, key, (offset, limit), reload=reload, lock_enabled=True)


def get_all_shares_count(reload: bool = False) -> int:
    return cached_count("SELECT COUNT(*) FROM shares", "all_shares_count", lock_enabled=True)


def get_artist_shares(artist_id, service, reload=False):
    key = f"artist_shares:{service}:{artist_id}"
    query = """
        SELECT *
        FROM shares s
        INNER JOIN lookup_share_relationships lsr on s.id = lsr.share_id
        WHERE lsr.user_id = %s AND lsr.service = %s
        ORDER BY s.id DESC
    """
    # todo CONSTRAINT lookup_share_relationships_pkey PRIMARY KEY (share_id, service, user_id) should be user_id, service, share_id or we have other index
    return cached_query(query, key, (artist_id, service), reload=reload)


def get_artist_share_count(service: str, artist_id: str, reload=False):
    return 0  # disabled for now while feature is off
    key = f"artist_share_count:{service}:{artist_id}"
    query = """
        SELECT COUNT(*)
        FROM lookup_share_relationships lsr
        WHERE lsr.user_id = %s AND lsr.service = %s
    """
    return cached_count(query, key, (service, artist_id), reload)


def get_files_for_share(share_id: int, reload=False):
    key = f"share_files:{share_id}"
    query = """
        SELECT *
        FROM file_share_relationships fsr
        LEFT JOIN files f
        ON fsr.file_id = f.id
        WHERE share_id = %s
        ORDER frs.file_id DESC
    """
    return cached_query(query, key, (share_id,), reload=reload)
