"""Tests — Spec 039 action catalog."""

from __future__ import annotations

import sqlite3
import unittest

from app import action_catalog


class TestActionCatalog(unittest.TestCase):
    def setUp(self):
        self.conn = sqlite3.connect(":memory:")
        self.conn.row_factory = sqlite3.Row
        action_catalog.init_schema(self.conn)
        action_catalog.load_base_catalog.cache_clear()

    def tearDown(self):
        action_catalog.load_base_catalog.cache_clear()
        self.conn.close()

    def test_export_has_executive_map(self):
        data = action_catalog.export_catalog(self.conn, edit_enabled=True)
        self.assertGreaterEqual(len(data["executive_map"]), 10)
        self.assertGreaterEqual(data["stats"]["action_count"], 50)

    def test_override_persists(self):
        action_catalog.set_action_override(
            self.conn,
            action_id="desk.auth.user.approve_registration",
            role_id="technician",
            level="full",
            username="root",
        )
        data = action_catalog.export_catalog(self.conn, edit_enabled=True)
        action = next(a for a in data["actions"] if a["id"] == "desk.auth.user.approve_registration")
        self.assertEqual(action["effective"]["technician"], "full")
        self.assertIn("technician", action["overridden_roles"])

    def test_reset_override(self):
        action_catalog.set_action_override(
            self.conn,
            action_id="vm123_openpanel.site.delete",
            role_id="devops",
            level="full",
            username="root",
        )
        action_catalog.set_action_override(
            self.conn,
            action_id="vm123_openpanel.site.delete",
            role_id="devops",
            level="none",
            username="root",
            reset=True,
        )
        data = action_catalog.export_catalog(self.conn, edit_enabled=True)
        action = next(a for a in data["actions"] if a["id"] == "vm123_openpanel.site.delete")
        self.assertEqual(action["effective"]["devops"], "none")


if __name__ == "__main__":
    unittest.main()
