# edited by glg
from importlib import import_module


class SyncBootstrapAdapterService:
    """
    Adapter sinkronisasi bootstrap agar modul auth tidak hard-depend
    ke modul sinkronisasi pada level import statis.
    """

    def __init__(self, model_factory=None, api_factory=None):
        self.model_factory = model_factory
        self.api_factory = api_factory

    def _build_model(self):
        if callable(self.model_factory):
            return self.model_factory()
        module = import_module("pypos.modules.sinkronisasi.models.sinkron_model")
        model_cls = getattr(module, "SinkronModel")
        return model_cls()

    def _build_api(self):
        if callable(self.api_factory):
            return self.api_factory()
        module = import_module("pypos.modules.sinkronisasi.services.sync_api_service")
        api_cls = getattr(module, "SyncApiService")
        return api_cls()

    def sync_per_employee(self, *, machine_id, cabang_id):
        if not machine_id or not cabang_id:
            raise RuntimeError("Device/cabang belum valid untuk sinkronisasi akun login.")

        model_sync = self._build_model()
        sync_api = self._build_api()
        resp = sync_api.sync_data_server(
            model=model_sync,
            machine_id=machine_id,
            cabang_id=cabang_id,
            tables=["per_employee"],
            force_full_tables=["per_employee"],
        )
        data_block = (resp.get("data") or {}).get("per_employee") if isinstance(resp, dict) else []
        if isinstance(data_block, dict) and "new" in data_block:
            rows = data_block.get("new") or []
        else:
            rows = data_block or []
        if rows:
            model_sync.apply_sync_result("per_employee", rows, full_refresh=True)
        return int(len(rows or []))
