package de.softwareapp_hb.privateqrscanner.util

import android.provider.ContactsContract
import android.provider.ContactsContract.CommonDataKinds.Organization
import android.provider.ContactsContract.CommonDataKinds.StructuredName
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class IntentsTest {

    @Test
    fun buildAddContactIntent_setsCompanyAndTitleExtras() {
        val parsed = ParsedContact(
            fullName = "John Doe",
            organization = "TEC-IT",
            title = "Position",
            phones = listOf("+43 7252 72720"),
            emails = listOf("support@tec-it.com"),
            address = "203 New York Ave, New York, NY 11377, USA"
        )

        val intent = Intents.buildAddContactIntent(parsed, "raw")

        assertEquals("TEC-IT", intent.getStringExtra(ContactsContract.Intents.Insert.COMPANY))
        assertEquals("TEC-IT", intent.getStringExtra(Organization.COMPANY))
        assertEquals("Position", intent.getStringExtra(ContactsContract.Intents.Insert.JOB_TITLE))
        assertEquals("Position", intent.getStringExtra(Organization.TITLE))
    }

    @Test
    fun buildAddContactIntent_keepsOnlyOriginalNoteText() {
        val parsed = ParsedContact(
            fullName = "John Doe",
            organization = "TEC-IT",
            title = "Position",
            note = "Existing note"
        )

        val intent = Intents.buildAddContactIntent(parsed, "raw")
        val notes = intent.getStringExtra(ContactsContract.Intents.Insert.NOTES).orEmpty()

        assertEquals("Existing note", notes)
    }

    @Test
    fun buildAddContactIntent_normalizesDuplicatedLastName() {
        val parsed = ParsedContact(
            fullName = "Alice Mason Mason",
            givenName = "Alice",
            familyName = "Mason"
        )

        val intent = Intents.buildAddContactIntent(parsed, "raw")
        val insertedName = intent.getStringExtra(ContactsContract.Intents.Insert.NAME)
        val dataRows = intent.getParcelableArrayListExtra<android.content.ContentValues>(
            ContactsContract.Intents.Insert.DATA
        )

        // When structured name is present, do not send plain NAME to avoid OEM split issues.
        assertNull(insertedName)
        val structured = dataRows?.firstOrNull()
        assertEquals(StructuredName.CONTENT_ITEM_TYPE, structured?.getAsString(ContactsContract.Data.MIMETYPE))
        assertEquals("Alice", structured?.getAsString(StructuredName.GIVEN_NAME))
        assertEquals("Mason", structured?.getAsString(StructuredName.FAMILY_NAME))
        assertEquals("Alice Mason", structured?.getAsString(StructuredName.DISPLAY_NAME))

        // Keep explicit check for normalized display form.
        assertEquals("Alice Mason", structured?.getAsString(StructuredName.DISPLAY_NAME))
    }
}
