# (c) cavaliba.com - test / FieldDatetime - bare date input

"""
A bare 'YYYY-MM-DD' given to a datetime field - the natural thing to type in
hand-written YAML/JSON or the RAW code editor - defaults to midnight instead of
being dropped.

It used to normalize to None, and because merge_import()/merge_request() just
skip what doesn't parse, the field was silently WIPED rather than reported as
invalid: the worst of the three outcomes, and invisible until the next read.

These tests pin the midnight default and, around it, that the fallback didn't
make the parser lax: a bad date, a time-only value and a half-written time are
all still rejected.
"""

from django.test import RequestFactory, TestCase

from app_data.fieldtypes.field_datetime import FieldDatetime


class TestFieldDatetimeDateOnly(TestCase):
    FIELDSCHEMA = {"dataformat": "datetime", "cardinal_max": 0}

    def field(self):
        """A fresh multi-valued FieldDatetime with no initial value."""
        return FieldDatetime(fieldname="dt", fieldschema=self.FIELDSCHEMA, alljson={})

    def test_merge_import_date_only_defaults_to_midnight(self):
        f = self.field()
        f.merge_import("2026-01-15")
        self.assertEqual(f.value, ["2026-01-15 00:00:00"])

    def test_merge_request_date_only_defaults_to_midnight(self):
        f = self.field()
        request = RequestFactory().post("/", {"dt": "2026-01-15"})
        f.merge_request(request)
        self.assertEqual(f.value, ["2026-01-15 00:00:00"])

    def test_is_valid_accepts_a_bare_date(self):
        f = self.field()
        f.value = ["2026-01-15"]
        self.assertTrue(f.is_valid())

    def test_merge_import_list_mixes_bare_dates_and_timestamps(self):
        f = self.field()
        f.merge_import(["2026-01-15", "2026-01-16 10:20:30", "2026-01-17T08:00"])
        self.assertEqual(
            f.value,
            ["2026-01-15 00:00:00", "2026-01-16 10:20:30", "2026-01-17 08:00:00"],
        )

    def test_date_only_does_not_shadow_a_full_timestamp(self):
        # '%Y-%m-%d' sits last in ACCEPTED_FORMATS; a value carrying a time must
        # still match the fuller format and keep its hh:mm:ss
        f = self.field()
        f.merge_import("2026-01-15 10:20:30")
        self.assertEqual(f.value, ["2026-01-15 10:20:30"])

    def test_impossible_date_is_still_rejected(self):
        f = self.field()
        f.merge_import("2026-02-30")
        self.assertEqual(f.value, [])

    def test_date_with_a_trailing_separator_is_still_rejected(self):
        f = self.field()
        f.merge_import("2026-01-15T")
        self.assertEqual(f.value, [])

    def test_time_only_is_still_rejected(self):
        f = self.field()
        f.merge_import("10:20:30")
        self.assertEqual(f.value, [])
