package app.mealsmadeeasy.api.user;

import jakarta.persistence.*;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

@Entity(name = "User")
@Table(name = "\"user\"")
@Data
public class User implements UserDetails {

    public static User getDefaultDraft() {
        final var user = new User();
        user.setEnabled(true);
        user.setExpired(false);
        user.setLocked(false);
        user.setCredentialsExpired(false);
        return user;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false)
    private Integer id;

    @Column(unique = true, nullable = false)
    private String username;

    @Column(unique = true, nullable = false)
    private String email;

    @Column(nullable = false)
    private String password;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
    private final Set<UserGrantedAuthority> authorities = new HashSet<>();

    @Column(nullable = false)
    private Boolean enabled;

    @Column(nullable = false)
    private Boolean expired;

    @Column(nullable = false)
    private Boolean locked;

    @Column(nullable = false)
    private Boolean credentialsExpired;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    public void addAuthority(UserGrantedAuthority userGrantedAuthority) {
        this.authorities.add(userGrantedAuthority);
    }

    public void addAuthorities(Set<? extends UserGrantedAuthority> userGrantedAuthorities) {
        userGrantedAuthorities.forEach(this::addAuthority);
    }

    public void removeAuthority(UserGrantedAuthority userGrantedAuthority) {
        this.authorities.remove(userGrantedAuthority);
    }

    @Override
    public boolean isAccountNonExpired() {
        return !this.expired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !this.locked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return !this.credentialsExpired;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }

}
