/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */

package org.grails.orm.hibernate.cfg.domainbinding

import org.hibernate.MappingException
import org.hibernate.mapping.Column
import org.hibernate.mapping.Table
import org.hibernate.mapping.UniqueKey
import spock.lang.Specification
import spock.lang.Subject
import spock.lang.Unroll

import java.nio.charset.StandardCharsets
import java.security.MessageDigest

import org.grails.orm.hibernate.cfg.domainbinding.util.UniqueNameGenerator

class UniqueNameGeneratorSpec extends Specification {

    @Subject
    UniqueNameGenerator generator = new UniqueNameGenerator()

    def "should generate a unique name based on table and column names"() {
        given: "A unique key with a table and several columns"
        def table = new Table("test", "person")
        def column1 = new Column('first_name')
        def column2 = new Column('last_name')
        def uniqueKey = new UniqueKey(table)
        uniqueKey.addColumn(column1)
        uniqueKey.addColumn(column2)

        def expectedName = generateExpectedName("person", "first_name", "last_name")

        when: "the unique name is generated"
        generator.setGeneratedUniqueName(uniqueKey)

        then: "the name is correctly calculated"
        uniqueKey.getName() == expectedName
    }

    def "should throw MappingException if the unique key has no associated table"() {
        given: "A unique key without a table (using a subclass because UniqueKey constructor requires table)"
        def uniqueKey = new UniqueKey(null)
        uniqueKey.setName("my_uk")

        when: "an attempt is made to generate the name"
        generator.setGeneratedUniqueName(uniqueKey)

        then: "a MappingException is thrown with a descriptive message"
        def e = thrown(MappingException)
        e.message == "Unique Key my_uk does not have a table associated with it"
    }

    def "should generate a name based only on the table if no columns are present"() {
        given: "A unique key with a table but no columns"
        def table = new Table("test", "audit_log")
        def uniqueKey = new UniqueKey(table)

        def expectedName = generateExpectedName("audit_log")

        when: "the unique name is generated"
        generator.setGeneratedUniqueName(uniqueKey)

        then: "the name is generated correctly using only the table name"
        uniqueKey.getName() == expectedName
    }

    def "should filter out columns with blank or null names"() {
        given: "A unique key with valid, blank, and null column names"
        def table = new Table("test", "product")
        def column1 = new Column('sku')
        def column2 = new Column('')
        def column3 = new Column(null)
        
        def uniqueKey = Mock(UniqueKey)
        uniqueKey.getTable() >> table
        uniqueKey.getColumns() >> [column1, column2, column3]

        // Only valid names should be part of the hash
        def expectedName = generateExpectedName("product", "sku")

        when: "the unique name is generated"
        generator.setGeneratedUniqueName(uniqueKey)

        then: "the blank and null column names are ignored in the calculation"
        1 * uniqueKey.setName(expectedName)
    }

    /**
     * Helper method that mirrors the core logic of UniqueNameGenerator to create
     * a verifiable expected result without using hardcoded "magic" strings.
     */
    private String generateExpectedName(String... fields) {
        def ukString = fields.join('_')
        MessageDigest md = MessageDigest.getInstance("MD5")
        md.update(ukString.getBytes(StandardCharsets.UTF_8))
        String name = "UK" + new BigInteger(1, md.digest()).toString(16)
        if (name.length() > 30) {
            name = name.substring(0, 30)
        }
        return name
    }
}
