import json
import uuid

from django.test import Client, override_settings

from apps.sync.models import InboxEvent, Node, OutboxEvent, SyncChange
from apps.sync.services import emit, get_local_node, verify_request

from .base import BaseDataTestCase


@override_settings(DEBUG=True)
class SyncTests(BaseDataTestCase):
    def test_emit_creates_chained_outbox_event(self):
        node = get_local_node()
        first = emit(entity=self.agency, op_type="UPDATE", actor=self.admin, agency_id=self.agency.id)
        second = emit(entity=self.agency, op_type="UPDATE", actor=self.admin, agency_id=self.agency.id)
        self.assertEqual(second.local_seq, first.local_seq + 1)
        self.assertEqual(second.prev_hash, first.hash)
        self.assertNotEqual(second.hash, first.hash)

    def test_push_is_idempotent(self):
        node = get_local_node()
        op_id = str(uuid.uuid4())
        payload = {"protocol": "fablabs-sync/1", "node_id": str(node.node_id), "batch_id": str(uuid.uuid4()),
                   "events": [{"op_id": op_id, "op_type": "UPDATE", "entity_type": "members.Member",
                               "entity_id": str(uuid.uuid4()), "agency_id": None, "version": 2, "base_version": 1,
                               "local_seq": 1, "occurred_at": "2026-11-15T10:00:00Z",
                               "payload": {"first_name": "Sync"}, "prev_hash": "", "hash": "x"}]}
        client = Client()
        response = client.post("/synchronisation/v1/push", data=json.dumps(payload),
                               content_type="application/json", HTTP_X_NODE_ID=str(node.node_id))
        self.assertEqual(response.json()["results"][0]["status"], "APPLIED")
        response = client.post("/synchronisation/v1/push", data=json.dumps(payload),
                               content_type="application/json", HTTP_X_NODE_ID=str(node.node_id))
        self.assertEqual(response.json()["results"][0]["status"], "DUPLICATE")
        self.assertEqual(InboxEvent.objects.filter(op_id=op_id).count(), 1)
        self.assertEqual(SyncChange.objects.count(), 1)

    def test_push_rejects_out_of_scope_agency(self):
        node = get_local_node()
        node.role = "AGENCY"
        node.agency = self.agency
        node.save()
        payload = {"events": [{"op_id": str(uuid.uuid4()), "op_type": "UPDATE",
                               "entity_type": "members.Member", "entity_id": str(uuid.uuid4()),
                               "agency_id": str(self.other_agency.id), "version": 1, "base_version": 0,
                               "local_seq": 1, "payload": {}, "prev_hash": "", "hash": "x"}]}
        response = Client().post("/synchronisation/v1/push", data=json.dumps(payload),
                                 content_type="application/json", HTTP_X_NODE_ID=str(node.node_id))
        self.assertEqual(response.json()["results"][0]["status"], "REJECTED")
        node.role = "CENTRAL"
        node.agency = None
        node.save()


class HmacTests(BaseDataTestCase):
    def test_signature_verification_rejects_tampering(self):
        node = get_local_node()
        from django.test import RequestFactory
        factory = RequestFactory()
        body = b'{"events":[]}'
        request = factory.post("/sync/v1/push", data=body, content_type="application/json",
                               HTTP_X_NODE_ID=str(node.node_id), HTTP_X_TIMESTAMP="0",
                               HTTP_X_NONCE=str(uuid.uuid4()), HTTP_X_SIGNATURE="boiteux")
        ok, reason, _ = verify_request(request, body, "secret")
        self.assertFalse(ok)
        self.assertIn(reason, {"BAD_SIGNATURE", "CLOCK_SKEW"})
