package com.seven.ikar.kotlin.core.contacts

import android.content.Context
import android.provider.ContactsContract

data class DeviceContactRecord(
    val displayName: String,
    val normalizedPhoneNumber: String
)

class AndroidContactDiscoveryService(private val context: Context) {
    fun getContacts(): List<DeviceContactRecord> {
        val contentResolver = context.contentResolver ?: return emptyList()
        val contacts = linkedMapOf<String, DeviceContactRecord>()
        val projection = arrayOf(
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER
        )

        contentResolver.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            projection,
            null,
            null,
            "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} COLLATE NOCASE ASC"
        )?.use { cursor ->
            val nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
            val phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)

            while (cursor.moveToNext()) {
                val rawPhone = if (phoneIndex >= 0) cursor.getString(phoneIndex) else null
                val normalizedPhone = PhoneNumberNormalizer.normalize(rawPhone) ?: continue
                if (contacts.containsKey(normalizedPhone)) {
                    continue
                }

                val rawName = if (nameIndex >= 0) cursor.getString(nameIndex) else null
                val displayName = rawName?.trim().takeUnless { it.isNullOrBlank() } ?: normalizedPhone
                contacts[normalizedPhone] = DeviceContactRecord(displayName, normalizedPhone)
            }
        }

        return contacts.values.toList()
    }
}
