from __future__ import annotations

from sqlalchemy.orm import Session

from ..database.orm import SalaryConfigORM


class SalaryConfigRepository:
    """系统配置仓库：封装 salary_config 表的查询和保存。"""

    def __init__(self, session: Session):
        self.session = session

    def list_configs(self, *, config_group: str | None = None) -> list[SalaryConfigORM]:
        query = self.session.query(SalaryConfigORM)
        if config_group:
            query = query.filter(SalaryConfigORM.config_group == config_group)
        return query.order_by(SalaryConfigORM.config_group.asc(), SalaryConfigORM.id.asc()).all()

    def get_by_key(self, config_key: str) -> SalaryConfigORM | None:
        return self.session.query(SalaryConfigORM).filter(SalaryConfigORM.config_key == config_key).one_or_none()

    def require_by_key(self, config_key: str) -> SalaryConfigORM:
        config = self.get_by_key(config_key)
        if config is None:
            raise ValueError("配置项不存在")
        return config

    def upsert_config(
        self,
        *,
        config_key: str,
        config_name: str,
        config_group: str,
        config_value: str,
        value_type: str,
        is_enabled: bool = True,
        remark: str = "",
    ) -> SalaryConfigORM:
        config = self.get_by_key(config_key)
        if config is None:
            config = SalaryConfigORM(config_key=config_key)
            self.session.add(config)
        config.config_name = config_name
        config.config_group = config_group
        config.config_value = config_value
        config.value_type = value_type
        config.is_enabled = is_enabled
        config.remark = remark
        self.session.commit()
        self.session.refresh(config)
        return config

    def create_defaults(self, defaults: list[dict]) -> int:
        created = 0
        for item in defaults:
            if self.get_by_key(item["config_key"]) is not None:
                continue
            self.session.add(SalaryConfigORM(**item))
            created += 1
        if created:
            self.session.commit()
        return created
