package com.sonymusic.dx.persistence.converter;

import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Converter(autoApply = false)
public class StringToDateConverter implements AttributeConverter<Date,String> {

   private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

    @Override
    public String convertToDatabaseColumn(Date attribute) {
        return attribute !=null ?formatter.format(attribute):null;
    }

    @Override
    public Date convertToEntityAttribute(String dbDate) {
        try {
            return dbDate !=null ? formatter.parse(dbDate) :null;
        } catch (ParseException e) {
            throw new RuntimeException("Could not parse date: ",e);
        }
    }
}
