package ru.soune.nocopy.entity.user;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import jakarta.validation.constraints.Size;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import ru.soune.nocopy.entity.company.Company;
import ru.soune.nocopy.entity.tarif.TariffInfo;
import ru.soune.nocopy.entity.tarif.TariffStatus;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "users")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@EntityListeners(AuditingEntityListener.class)
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long Id;

    @Column(name = "full_name", nullable = false)
    private String fullName;

    @Size(max = 1024)
    @Column(name = "email", nullable = false, length = 1024, unique = true)
    private String email;

    @Column(name = "email_verified")
    private boolean emailVerified = false;

    @Column(nullable = false)
    @Size(min = 6)
    @JsonIgnore
    private String password;

    @Size(min = 11, max = 14)
    @Column(unique = true)
    private String phone;

    @Enumerated(EnumType.STRING)
    @Column(name = "subscription_type", nullable = false, length = 20)
    private SubscriptionType subscriptionType = SubscriptionType.DEMO;

    @Enumerated(EnumType.STRING)
    @Column(name = "gender")
    private GenderType genderType = GenderType.MALE;

    @Column(name = "birthday")
    private LocalDate birthday;

    @CreatedDate
    @Column(name = "created_at", updatable = false, nullable = false)
    private LocalDateTime createdAt;

    @Column(name = "last_login_at")
    private LocalDateTime lastLoginAt;

    @Column(name = "is_active")
    private boolean isActive = false;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonIgnore
    @ToString.Exclude
    private List<AuthToken> tokens = new ArrayList<>();

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonIgnore
    @ToString.Exclude
    private List<UserContent> userContents = new ArrayList<>();

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonIgnore
    private ProtectedFileCheck protectedFileCheck;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id")
    @ToString.Exclude
    private Company company;

    @Column(name = "permissions")
    private Long userPermissions = Permission.DEFAULT_USER_PERMISSIONS;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "personal_tariff_info_id")
    @ToString.Exclude
    private TariffInfo personalTariffInfo;

    @Column(name = "failed_login_attempts")
    @ColumnDefault("0")
    private Integer failedLoginAttempts = 0;

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonIgnore
    @ToString.Exclude
    private UserNotActive userNotActive;

    @Column(name = "verification_status")
    @Enumerated(EnumType.STRING)
    private ModerationStatus verificationStatus = ModerationStatus.NOT_VERIFIED;

    public TariffInfo getActiveTariffInfo() {
        if (company != null && company.getTariffInfo() != null) {
            return company.getTariffInfo();
        }
        return personalTariffInfo;
    }

    public boolean hasTariffAccess() {
        TariffInfo activeTariff = getActiveTariffInfo();
        if (activeTariff == null) {
            return false;
        }

        return activeTariff.getStatus() == TariffStatus.ACTIVE &&
                LocalDateTime.now().isBefore(activeTariff.getEndTariff());
    }

    public boolean canLogin() {
        return Permission.canLogin(this.userPermissions);
    }

    public boolean canManageCompanySettings() {
        return Permission.canManageCompanySettings(this.userPermissions);
    }

    public void grantPermission(long permissionBit) {
        this.userPermissions = Permission.addPermission(this.userPermissions, permissionBit);
    }

    public void removePermission(long permissionBit) {
        this.userPermissions = Permission.removePermission(this.userPermissions, permissionBit);
    }

    public boolean hasPermission(long permissionBit) {
        return Permission.hasPermission(this.userPermissions, permissionBit);
    }

    public String getCompanyName() {
        if (company != null) {
            return company.getCompanyName();
        } else {
            return null;
        }
    }
}
