import json
from typing import List

from maps_adv.adv_store.lib.db import db
from maps_adv.adv_store.v2.lib.data_managers import sqls
from maps_adv.adv_store.v2.lib.data_managers.campaigns import (
    CampaignsChangeLogActionName,
)

__all__ = [
    "insert_campaign_change_log",
    "refresh_campaigns_change_logs",
    "CampaignsChangeLogActionName",
]

_sql_insert = (
    sqls.insert_campaigns_change_log.replace("$1", "(:campaign_id)")
    .replace("$2", "(:author_id)")
    .replace("$3", "(:system_metadata)")
)
_sql_refresh = sqls.refresh_campaigns_change_logs_status_and_states.replace(
    "$1", "(:ids)"
)


async def insert_campaign_change_log(
    *, campaign_id: int, author_id: int = 0, action_name: str, **kwargs
) -> int:
    return await db.rw.execute(
        _sql_insert,
        dict(
            campaign_id=campaign_id,
            author_id=author_id,
            system_metadata=json.dumps({"action": action_name, **kwargs}),
        ),
    )


async def refresh_campaigns_change_logs(*, ids: List[int]):
    return await db.rw.fetch_all(_sql_refresh, dict(ids=ids))
