package models

import (
	"database/sql"
	"strings"
	"time"
)

type CustomTime struct {
	sql.NullTime
}

func (ct *CustomTime) UnmarshalJSON(b []byte) error {
	s := strings.Trim(string(b), `"`)
	if s == "" || s == "null" {
		ct.Valid = false
		return nil
	}

	// DESTEKLENEN TÜM FORMATLAR
	layouts := []string{
		time.RFC3339,          // 2025-11-21T00:10:27Z
		"2006-01-02T15:04:05", // 2025-11-21T00:10:27
		"2006-01-02 15:04:05", // 2025-11-21 00:10:27 ← FRONTEND FORMATIN!
	}

	for _, layout := range layouts {
		if t, err := time.Parse(layout, s); err == nil {
			ct.Time = t
			ct.Valid = true
			return nil
		}
	}

	// Hâlâ parse edemediyse → invalid kabul et
	ct.Valid = false
	return nil
}

func (ct CustomTime) MarshalJSON() ([]byte, error) {
	if ct.Valid {
		return []byte(`"` + ct.Time.Format("2006-01-02 15:04:05") + `"`), nil
	}
	return []byte(`null`), nil
}
