package io.delphiplatform.api.v3.model;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.delphiplatform.api.util.model.ModelUtils;
import io.delphiplatform.api.v3.rdb.entity.PlaylistProjection;
import io.delphiplatform.api.v3.rdb.entity.apple.music.AppleMusicPlaylistOwnerEntity;
import io.delphiplatform.api.v3.rdb.entity.spotify.SpotifyPlaylistOwnerEntity;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;

@Builder
@Getter
@EqualsAndHashCode
@ToString
public class PlaylistOwner {

    @JsonProperty("username")
    private String username;
    @JsonProperty("display_name")
    private String displayName;
    @JsonProperty("owner_country_code")
    private String ownerCountryCode;
    @JsonProperty("owner_category")
    private PlaylistOwnerCategory ownerCategory;
    @JsonProperty("dsp")
    private Dsp dsp;

    public static PlaylistOwner from(SpotifyPlaylistOwnerEntity entity) {
        if (entity == null) {
            return null;
        }

        String displayName = entity.getDisplayName() != null
            ? entity.getDisplayName()
            : ModelUtils.removeDspFromPlaylistOwnerUserName(entity.getUsername());

        return PlaylistOwner.builder()
            .username(entity.getUsername())
            .displayName(displayName)
            .ownerCountryCode(entity.getOwnerCountryCode())
            .ownerCategory(PlaylistOwnerCategory.from(entity.getOwnerCategory()))
            .dsp(Dsp.from(entity.getDsp()))
            .build();
    }

    public static PlaylistOwner from(AppleMusicPlaylistOwnerEntity entity) {
        if (entity == null) {
            return null;
        }

        String displayName = entity.getDisplayName() != null
            ? entity.getDisplayName()
            : ModelUtils.removeDspFromPlaylistOwnerUserName(entity.getUsername());

        return PlaylistOwner.builder()
            .username(entity.getUsername())
            .displayName(displayName)
            .ownerCountryCode(entity.getOwnerCountryCode())
            .ownerCategory(PlaylistOwnerCategory.from(entity.getOwnerCategory()))
            .dsp(Dsp.from(entity.getDsp()))
            .build();
    }

    public static PlaylistOwner from(PlaylistProjection entity) {
        if (entity == null || entity.getOwnerUserName() == null) {
            //entity.getOwnerUserName() is in fact PK for playlist_owner tables so if it is null - owner is missing
            return null;
        }
        return PlaylistOwner.builder()
            .username(entity.getOwnerUserName())
            .displayName(entity.getOwnerDisplayName())
            .ownerCountryCode(entity.getOwnerCountryCode())
            .ownerCategory(PlaylistOwnerCategory.from(entity))
            .dsp(new Dsp()
                .dspId(entity.getDspId())
                .name(entity.getDspName())
                .slug(entity.getDspSlug()))
            .build();
    }
}
