package stwbremen

import (
	"encoding/json"
	"time"
)

type TimeOnly struct {
	time.Time
}

// UnmarshalJSON parses a JSON string in HH:MM:SS format into a TimeOnly
func (t *TimeOnly) UnmarshalJSON(b []byte) error {
	var s string
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	parsed, err := time.Parse(time.TimeOnly, s)
	if err != nil {
		return err
	}
	t.Time = parsed
	return nil
}

// MarshalJSON converts the TimeOnly to a JSON string in HH:MM:SS format
func (t TimeOnly) MarshalJSON() ([]byte, error) {
	return json.Marshal(t.Format(time.TimeOnly))
}

type DateOnly struct {
	time.Time
}

// UnmarshalJSON parses a JSON string in YYYY-MM-DD format into a DateOnly
func (d *DateOnly) UnmarshalJSON(b []byte) error {
	var s string
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	parsed, err := time.Parse(time.DateOnly, s)
	if err != nil {
		d.Time = time.Time{}
	} else {
		d.Time = parsed
	}
	return nil
}

// MarshalJSON converts the DateOnly to a JSON string in YYYY-MM-DD format
func (d DateOnly) MarshalJSON() ([]byte, error) {
	return json.Marshal(d.Format(time.DateOnly))
}
