from codegen.models import Program, stmt

from sera.models import Class, Package


def make_index(cls: Class, pkg: Package):
    outmod = pkg.module("index")

    export_types = []
    export_iso_types = []  # isolatedModules required separate export type clause

    program = Program()
    program.import_(
        f"@.models.{pkg.dir.name}.{cls.get_tsmodule_name()}.{cls.name}", True
    )
    export_types.append(cls.name)
    if cls.db is not None:
        # only import the id if this class is stored in the database
        program.import_(
            f"@.models.{pkg.dir.name}.{cls.get_tsmodule_name()}.{cls.name}Id", True
        )
        export_iso_types.append(f"{cls.name}Id")

    program.import_(
        f"@.models.{pkg.dir.name}.{cls.get_tsmodule_name()}-schema.{cls.name}Schema",
        True,
    )
    program.import_(
        f"@.models.{pkg.dir.name}.{cls.get_tsmodule_name()}-query.{cls.name}Query",
        True,
    )
    export_types.append(f"{cls.name}Schema")
    export_iso_types.append(f"{cls.name}Query")
    program.import_(
        f"@.models.{pkg.dir.name}.{cls.get_tsmodule_name()}-schema.Typed{cls.name}Schema",
        True,
    )
    export_types.append(f"Typed{cls.name}Schema")

    program.import_(
        f"@.models.{pkg.dir.name}.draft-{cls.get_tsmodule_name()}.Draft{cls.name}",
        True,
    )
    export_types.append(f"Draft{cls.name}")
    if cls.db is not None:
        program.import_(
            f"@.models.{pkg.dir.name}.{cls.get_tsmodule_name()}-table.{cls.name}Table",
            True,
        )
        export_types.append(f"{cls.name}Table")

    program.root(
        stmt.LineBreak(),
        stmt.TypescriptStatement("export { %s };" % (", ".join(export_types))),
        (
            stmt.TypescriptStatement(
                "export type { %s };" % (", ".join(export_iso_types))
            )
        ),
    )

    outmod.write(program)
