"""Export SQL aux noms de tables de la production : seules les instructions de structure sont reecrites."""

from django.test import SimpleTestCase

from facturation.management.commands.exporter_base_production import build_rewriter, production_table_names


class ExportProductionRewriteTests(SimpleTestCase):
    def setUp(self):
        self.rewrite = build_rewriter(
            {"g_erreur_action": "G_Erreur_action", "g_erreur_adresseip": "G_Erreur_adresseip"}
        )

    def test_models_with_capital_letters_are_mapped(self):
        mapping = production_table_names()
        self.assertEqual(mapping["g_erreur_action"], "G_Erreur_action")
        self.assertEqual(mapping["g_taux_regletaux"], "G_taux_regletaux")
        self.assertEqual(
            mapping["g_affectation_ligneoperationaffectation_transferts"],
            "G_Affectation_ligneoperationaffectation_transferts",
        )
        self.assertNotIn("facturation_commande", mapping)

    def test_structure_statements_get_the_production_name(self):
        for line, expected in (
            (b"DROP TABLE IF EXISTS `g_erreur_action`;\n", b"DROP TABLE IF EXISTS `G_Erreur_action`;\n"),
            (b"CREATE TABLE `g_erreur_action` (\n", b"CREATE TABLE `G_Erreur_action` (\n"),
            (b"LOCK TABLES `g_erreur_action` WRITE;\n", b"LOCK TABLES `G_Erreur_action` WRITE;\n"),
            (
                b"/*!40000 ALTER TABLE `g_erreur_action` DISABLE KEYS */;\n",
                b"/*!40000 ALTER TABLE `G_Erreur_action` DISABLE KEYS */;\n",
            ),
            (
                b"  CONSTRAINT `fk_ip` FOREIGN KEY (`ip_id`) REFERENCES `g_erreur_adresseip` (`id`)\n",
                b"  CONSTRAINT `fk_ip` FOREIGN KEY (`ip_id`) REFERENCES `G_Erreur_adresseip` (`id`)\n",
            ),
        ):
            self.assertEqual(self.rewrite(line), expected)

    def test_insert_header_is_renamed_but_values_are_never_touched(self):
        line = b"INSERT INTO `g_erreur_action` VALUES (1,'voir `g_erreur_action` dans la doc');\n"
        self.assertEqual(
            self.rewrite(line),
            b"INSERT INTO `G_Erreur_action` VALUES (1,'voir `g_erreur_action` dans la doc');\n",
        )

    def test_other_tables_and_plain_lines_are_left_alone(self):
        for line in (
            b"CREATE TABLE `facturation_commande` (\n",
            b"  `libelle` varchar(50) NOT NULL DEFAULT 'g_erreur_action',\n",
            b"INSERT INTO `facturation_commande` VALUES (1,'`g_erreur_action`');\n",
        ):
            self.assertEqual(self.rewrite(line), line)
