"""
Tests for production targets: UPSERT correctness, no race-condition duplicates.
"""
import json, pytest


class TestProductionTargets:
    def test_set_targets(self, gm_client):
        r = gm_client.post('/api/production/targets',
                           data=json.dumps({'targets': {'1': 50, '2': 30}}),
                           content_type='application/json',
                           headers={'X-CSRFToken': 'test-csrf-token'})
        assert r.status_code == 200

    def test_update_targets_no_duplicate(self, gm_client):
        """Submitting targets twice for the same date must not create duplicate rows."""
        payload = json.dumps({'targets': {'1': 60}})
        headers = {'X-CSRFToken': 'test-csrf-token'}
        gm_client.post('/api/production/targets', data=payload,
                       content_type='application/json', headers=headers)
        gm_client.post('/api/production/targets', data=payload,
                       content_type='application/json', headers=headers)
        # Read back and confirm single row
        r = gm_client.get('/api/production/targets')
        targets = json.loads(r.data)
        # Product 1 should appear exactly once
        assert list(targets.keys()).count('1') == 1

    def test_targets_get_returns_dict(self, gm_client):
        r = gm_client.get('/api/production/targets')
        assert r.status_code == 200
        data = json.loads(r.data)
        assert isinstance(data, dict)
