"""Tenant company profile stored in accounting_settings (company.* keys)."""
from __future__ import annotations

from uuid import UUID

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.foundation import AccountingSettings

COMPANY_FIELDS: dict[str, str] = {
    "legal_name": "",
    "trade_name": "",
    "national_id": "",
    "economic_code": "",
    "registration_number": "",
    "postal_code": "",
    "province": "",
    "city": "",
    "address": "",
    "phone": "",
    "mobile": "",
    "email": "",
    "website": "",
    "ceo_name": "",
    "accountant_name": "",
}


class CompanyProfileService:
    PREFIX = "company."

    def __init__(self, session: AsyncSession) -> None:
        self.session = session

    async def get_profile(self, tenant_id: UUID) -> dict[str, str]:
        stmt = select(AccountingSettings).where(
            AccountingSettings.tenant_id == tenant_id,
            AccountingSettings.key.like(f"{self.PREFIX}%"),
        )
        rows = list((await self.session.execute(stmt)).scalars().all())
        stored = {r.key[len(self.PREFIX) :]: (r.value or "") for r in rows}
        return {**COMPANY_FIELDS, **{k: stored.get(k, v) for k, v in COMPANY_FIELDS.items()}}

    async def update_profile(self, tenant_id: UUID, body: dict) -> dict[str, str]:
        for field in COMPANY_FIELDS:
            if field not in body:
                continue
            value = "" if body[field] is None else str(body[field]).strip()
            full_key = f"{self.PREFIX}{field}"
            stmt = select(AccountingSettings).where(
                AccountingSettings.tenant_id == tenant_id,
                AccountingSettings.key == full_key,
            )
            row = (await self.session.execute(stmt)).scalar_one_or_none()
            if row is None:
                self.session.add(
                    AccountingSettings(
                        tenant_id=tenant_id,
                        key=full_key,
                        value=value,
                        value_type="string",
                    )
                )
            else:
                row.value = value
        await self.session.flush()
        return await self.get_profile(tenant_id)
