package dev.fyloz.trial.colorrecipesexplorer.model

import dev.fyloz.trial.colorrecipesexplorer.model.validation.NullOrNotBlank
import java.util.*
import javax.persistence.*
import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotNull

private const val COMPANY_ID_NULL_MESSAGE = "Un identifiant est requis"
private const val COMPANY_NAME_NULL_MESSAGE = "Un nom est requis"

@Entity
data class Company(
        @Id
        @GeneratedValue(strategy = GenerationType.SEQUENCE)
        override val id: Long?,

        @Column(unique = true)
        override val name: String
) : NamedModel {
    override fun equals(other: Any?): Boolean = other is Company && name == other.name
    override fun hashCode(): Int = Objects.hash(name)
}


open class CompanySaveDto(
        @field:NotBlank(message = COMPANY_NAME_NULL_MESSAGE)
        val name: String
) : EntityDto<Company> {
    override fun toEntity(): Company = Company(null, name)
}


open class CompanyUpdateDto(
        @field:NotNull(message = COMPANY_ID_NULL_MESSAGE)
        val id: Long,

        @field:NullOrNotBlank(message = COMPANY_NAME_NULL_MESSAGE)
        val name: String?
) : EntityDto<Company> {
    override fun toEntity(): Company = Company(id, name ?: "")
}

// ==== DSL ====
fun company(
        id: Long? = null,
        name: String = "name",
        op: Company.() -> Unit = {}
) = Company(id, name).apply(op)

fun companySaveDto(
        name: String = "name",
        op: CompanySaveDto.() -> Unit = {}
) = CompanySaveDto(name).apply(op)

fun companyUpdateDto(
        id: Long = 0L,
        name: String? = "name",
        op: CompanyUpdateDto.() -> Unit = {}
) = CompanyUpdateDto(id, name).apply(op)
