package com.bcxin.tenant.domain.entities;

import com.bcxin.Infrastructures.entities.EntityAbstract;
import com.bcxin.Infrastructures.utils.UUIDUtil;
import com.bcxin.tenant.domain.DomainConstraint;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.sql.Timestamp;
import java.time.Instant;

/**
 *
 *
 */
@Getter
@Setter(AccessLevel.PROTECTED)
@Table(name = "tenant_employee_relations",uniqueConstraints = {
        @UniqueConstraint(name = DomainConstraint.UNIQUE_TENANT_EMPLOYEE_RELATIONS_TENANT_USER_ID_ORGANIZATION_ID,
        columnNames = {"tenant_user_id","organization_id"})
})
@Entity
public class TenantUserEmployeeRelationEntity extends EntityAbstract {

    @Id
    @Column(length = 50)
    private String id;

    /**
     * * 这边尝试过使用employee作为主键，但是一直报错:
     * * 就是插入的时候老是无法拿到employee的id作为主键，老是得到null作为主键的值.
     * * 但是配置一个id之后就可以正常保存
     */
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "employee_id", referencedColumnName = "id",
            foreignKey = @ForeignKey(name = "fk_tenant_employee_relation_tenant_employee_id",
                    value = ConstraintMode.CONSTRAINT))
    private EmployeeEntity employee;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "organization_id", referencedColumnName = "id",
            foreignKey = @ForeignKey(name = "fk_tenant_employee_relation_tenant_organization_id", value = ConstraintMode.CONSTRAINT))
    private OrganizationEntity organization;

    @Column(name = "created_time", nullable = false)
    private Timestamp createdTime;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "tenant_user_id", referencedColumnName = "id",
            foreignKey = @ForeignKey(name = "fk_tenant_employee_relation_tenant_user_id"))
    private TenantUserEntity tenantUser;

    protected TenantUserEmployeeRelationEntity() {
        this.setCreatedTime(Timestamp.from(Instant.now()));
    }

    public static TenantUserEmployeeRelationEntity create(TenantUserEntity tenantUser,
                                                          OrganizationEntity organization,
                                                          EmployeeEntity employee) {
        TenantUserEmployeeRelationEntity tenantUserEmployeeRelation = new TenantUserEmployeeRelationEntity();
        tenantUserEmployeeRelation.setEmployee(employee);
        tenantUserEmployeeRelation.setTenantUser(tenantUser);
        tenantUserEmployeeRelation.setOrganization(organization);
        tenantUserEmployeeRelation.setId(UUIDUtil.getShortUuid());

        return tenantUserEmployeeRelation;
    }
}
