"""Regression tests for canvas_api.get_or_create_folder."""

import os
import sys
import unittest
from unittest.mock import MagicMock, patch

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts"))

import canvas_api


def _mock_config():
    return {
        "token": "fake",
        "domain": "canvas.test.edu",
        "course_id": "99999",
        "base_url": "https://canvas.test.edu/api/v1",
        "course_url": "https://canvas.test.edu/api/v1/courses/99999",
        "headers": {"Authorization": "Bearer fake"},
    }


def _response(status, body=None):
    resp = MagicMock()
    resp.status_code = status
    resp.json.return_value = body if body is not None else {}
    return resp


class TestGetOrCreateFolder(unittest.TestCase):
    @patch("canvas_api.requests.post")
    @patch("canvas_api.requests.get")
    def test_returns_last_folder_id_from_by_path_list(self, mock_get, mock_post):
        mock_get.return_value = _response(
            200,
            [
                {"id": 1, "name": "course files"},
                {"id": 42, "name": "Mockup Interactives"},
            ],
        )

        result = canvas_api.get_or_create_folder(
            _mock_config(), "course files", "Mockup Interactives"
        )

        self.assertEqual(result, 42)
        mock_post.assert_not_called()

    @patch("canvas_api.requests.post")
    @patch("canvas_api.requests.get")
    def test_creates_folder_when_by_path_returns_404(self, mock_get, mock_post):
        mock_get.return_value = _response(404)
        mock_post.return_value = _response(
            201, {"id": 42, "name": "Mockup Interactives"}
        )

        result = canvas_api.get_or_create_folder(
            _mock_config(), "course files", "Mockup Interactives"
        )

        self.assertEqual(result, 42)
        mock_post.assert_called_once_with(
            "https://canvas.test.edu/api/v1/courses/99999/folders",
            headers={"Authorization": "Bearer fake"},
            json={
                "name": "Mockup Interactives",
                "parent_folder_path": "course files",
            },
            timeout=30,
        )

    @patch("canvas_api.requests.post")
    @patch("canvas_api.requests.get")
    def test_empty_by_path_list_falls_through_to_create(self, mock_get, mock_post):
        mock_get.return_value = _response(200, [])
        mock_post.return_value = _response(
            201, {"id": 42, "name": "Mockup Interactives"}
        )

        result = canvas_api.get_or_create_folder(
            _mock_config(), "course files", "Mockup Interactives"
        )

        self.assertEqual(result, 42)


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