from typing import Any

from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession


class CompanyRepository:
    def __init__(self, session: AsyncSession) -> None:
        self.session = session

    @staticmethod
    def _first_available(row: dict[str, Any], *keys: str, default: Any = "") -> Any:
        for key in keys:
            if key in row and row[key] is not None:
                return row[key]
        return default

    def _map_profile_row(self, row: dict[str, Any]) -> dict[str, Any]:
        logo_value = self._first_available(row, "logo", default=None)
        return {
            "id": int(self._first_available(row, "id", default=1) or 1),
            "nama_perusahaan": self._first_available(
                row, "namaperusahaan", "nama_perusahaan", default=""
            ),
            "alamat_perusahaan": self._first_available(
                row, "alamatperusahaan", "alamat_perusahaan", default=""
            ),
            "telepon_perusahaan": self._first_available(
                row, "telpperusahaan", "telepon_perusahaan", default=""
            ),
            "email_perusahaan": self._first_available(
                row, "emailperusahaan", "email_perusahaan", default=""
            ),
            "npwp_perusahaan": self._first_available(
                row, "npwpperusahaan", "npwp_perusahaan", default=""
            ),
            "footnote": self._first_available(row, "footnote", default=""),
            "has_logo": bool(logo_value),
            "ppn": self._first_available(row, "ppn", default=0),
            "metode_ppn": self._first_available(
                row, "metodeppn", "metode_ppn", default="TANPA PPN"
            ),
            "qty_decimal_places": int(
                self._first_available(
                    row, "qtydecimalplaces", "qty_decimal_places", default=0
                )
                or 0
            ),
            "db_schema_version": self._first_available(
                row, "dbschemaversion", "db_schema_version", default=""
            ),
            "db_schema_updated_at": self._first_available(
                row, "dbschemaupdatedat", "db_schema_updated_at", default=None
            ),
        }

    async def get_company_profile(self) -> dict[str, Any] | None:
        result = await self.session.execute(
            text(
                """
                SELECT *
                FROM msperusahaan
                ORDER BY id
                LIMIT 1
                """
            )
        )
        row = result.mappings().one_or_none()
        return self._map_profile_row(dict(row)) if row else None

    async def get_report_profile(self) -> dict[str, Any] | None:
        profile = await self.get_company_profile()
        if profile is None:
            return None
        return {
            "nama": profile["nama_perusahaan"],
            "alamat": profile["alamat_perusahaan"],
            "telepon": profile["telepon_perusahaan"],
            "email": profile["email_perusahaan"],
            "npwp": profile["npwp_perusahaan"],
            "footnote": profile["footnote"],
        }
