from __future__ import annotations

from sera.make.ts_frontend.make_class_schema import make_class_schema
from sera.make.ts_frontend.make_draft_model import make_draft
from sera.make.ts_frontend.make_index import make_index
from sera.make.ts_frontend.make_model import make_normal
from sera.make.ts_frontend.make_query import make_query
from sera.make.ts_frontend.make_table import make_table
from sera.models import Package, Schema


def make_typescript_data_model(schema: Schema, target_pkg: Package):
    """Generate TypeScript data model from the schema. The data model aligns with the public data model in Python, not the database model."""
    # mapping from type alias of idprop to its real type
    idprop_aliases = {}
    for cls in schema.classes.values():
        idprop = cls.get_id_property()
        if idprop is not None:
            idprop_aliases[f"{cls.name}Id"] = (
                idprop.get_data_model_datatype().get_typescript_type()
            )

    for cls in schema.topological_sort():
        pkg = target_pkg.pkg(cls.get_tsmodule_name())
        make_normal(cls, pkg)
        make_draft(schema, cls, pkg, idprop_aliases)
        make_query(schema, cls, pkg)
        make_table(cls, pkg)
        make_class_schema(schema, cls, pkg)

        make_index(cls, pkg)
