# -*- coding: utf-8 -*-
"""平台券核销任务"""

import json

from .base_task import BaseTask, TaskContext
from loaders.facts.coupon_usage import CouponUsageLoader
from models.parsers import TypeParser


class CouponUsageTask(BaseTask):
    """同步平台券验券/核销记录"""

    def get_task_code(self) -> str:
        return "COUPON_USAGE"

    def extract(self, context: TaskContext) -> dict:
        params = self._merge_common_params(
            {
                "siteId": context.store_id,
                "startTime": TypeParser.format_timestamp(context.window_start, self.tz),
                "endTime": TypeParser.format_timestamp(context.window_end, self.tz),
            }
        )
        records, _ = self.api.get_paginated(
            endpoint="/Promotion/GetOfflineCouponConsumePageList",
            params=params,
            page_size=self.config.get("api.page_size", 200),
            data_path=("data",),
        )
        return {"records": records}

    def transform(self, extracted: dict, context: TaskContext) -> dict:
        parsed, skipped = [], 0
        for raw in extracted.get("records", []):
            mapped = self._parse_usage(raw, context.store_id)
            if mapped:
                parsed.append(mapped)
            else:
                skipped += 1
        return {
            "records": parsed,
            "fetched": len(extracted.get("records", [])),
            "skipped": skipped,
        }

    def load(self, transformed: dict, context: TaskContext) -> dict:
        loader = CouponUsageLoader(self.db)
        inserted, updated, loader_skipped = loader.upsert_coupon_usage(
            transformed["records"]
        )
        return {
            "fetched": transformed["fetched"],
            "inserted": inserted,
            "updated": updated,
            "skipped": transformed["skipped"] + loader_skipped,
            "errors": 0,
        }

    def _parse_usage(self, raw: dict, store_id: int) -> dict | None:
        usage_id = TypeParser.parse_int(raw.get("id"))
        if not usage_id:
            self.logger.warning("跳过缺少券核销ID的记录: %s", raw)
            return None

        return {
            "store_id": store_id,
            "usage_id": usage_id,
            "coupon_code": raw.get("coupon_code"),
            "coupon_channel": raw.get("coupon_channel"),
            "coupon_name": raw.get("coupon_name"),
            "sale_price": TypeParser.parse_decimal(raw.get("sale_price")),
            "coupon_money": TypeParser.parse_decimal(raw.get("coupon_money")),
            "coupon_free_time": TypeParser.parse_int(raw.get("coupon_free_time")),
            "use_status": raw.get("use_status"),
            "create_time": TypeParser.parse_timestamp(
                raw.get("create_time") or raw.get("createTime"), self.tz
            ),
            "consume_time": TypeParser.parse_timestamp(
                raw.get("consume_time") or raw.get("consumeTime"), self.tz
            ),
            "operator_id": TypeParser.parse_int(raw.get("operator_id")),
            "operator_name": raw.get("operator_name"),
            "table_id": TypeParser.parse_int(raw.get("table_id")),
            "site_order_id": TypeParser.parse_int(raw.get("site_order_id")),
            "group_package_id": TypeParser.parse_int(raw.get("group_package_id")),
            "coupon_remark": raw.get("coupon_remark"),
            "deal_id": raw.get("deal_id"),
            "certificate_id": raw.get("certificate_id"),
            "verify_id": raw.get("verify_id"),
            "is_delete": raw.get("is_delete"),
            "raw_data": json.dumps(raw, ensure_ascii=False),
        }
