from __future__ import annotations

from fastapi.testclient import TestClient


class TestProjectLifecycle:
    def test_project_create_update_delete_flow(self, client: TestClient) -> None:
        # Initial state: no projects listed on the UI page
        response = client.get("/projects/ui")
        assert response.status_code == 200
        assert "No projects yet" in response.text

        # Create a project via the HTML form submission
        create_payload = {
            "name": "Lifecycle Mine",
            "location": "Nevada",
            "operation_type": "open_pit",
            "description": "Initial description",
        }
        response = client.post(
            "/projects/create",
            data=create_payload,
            follow_redirects=False,
        )
        assert response.status_code == 303
        assert response.headers["Location"].endswith("/projects/ui")

        # Project should now appear on the list page
        response = client.get("/projects/ui")
        assert response.status_code == 200
        assert "Lifecycle Mine" in response.text
        assert "Nevada" in response.text

        # Fetch the project via API to obtain its identifier
        response = client.get("/projects")
        assert response.status_code == 200
        projects = response.json()
        assert len(projects) == 1
        project_id = projects[0]["id"]

        # Update the project using the API endpoint
        update_payload = {
            "location": "Arizona",
            "description": "Updated description",
        }
        response = client.put(f"/projects/{project_id}", json=update_payload)
        assert response.status_code == 200
        body = response.json()
        assert body["location"] == "Arizona"
        assert body["description"] == "Updated description"

        # Verify the UI detail page reflects the updates
        response = client.get(f"/projects/{project_id}/view")
        assert response.status_code == 200
        assert "Arizona" in response.text
        assert "Updated description" in response.text

        # Delete the project using the API endpoint
        response = client.delete(f"/projects/{project_id}")
        assert response.status_code == 204

        # Ensure the list view returns to the empty state
        response = client.get("/projects/ui")
        assert response.status_code == 200
        assert "No projects yet" in response.text
        assert "Lifecycle Mine" not in response.text
