package publicreport

import (
	"context"
	"fmt"

	"source.gleipnir.technology/Gleipnir/nidus-sync/db"
	modelcomms "source.gleipnir.technology/Gleipnir/nidus-sync/db/gen/nidus-sync/comms/model"
	querycomms "source.gleipnir.technology/Gleipnir/nidus-sync/db/query/comms"
	"source.gleipnir.technology/Gleipnir/nidus-sync/platform/types"
)

func ContactSimplesFromIDs(ctx context.Context, txn db.Ex, contact_ids []int64) ([]types.ContactSimple, error) {
	contacts, err := querycomms.ContactsFromIDs(ctx, txn, contact_ids)
	if err != nil {
		return nil, fmt.Errorf("contacts from ids: %w", err)
	}
	contact_emails, err := querycomms.ContactEmailByContactIDs(ctx, txn, contact_ids)
	if err != nil {
		return nil, fmt.Errorf("contact emails from ids: %w", err)
	}
	contact_phones, err := querycomms.ContactPhoneByContactIDs(ctx, txn, contact_ids)
	if err != nil {
		return nil, fmt.Errorf("contact phone by contact ids: %w", err)
	}
	e164s := make([]string, 0)
	for _, v := range contact_phones {
		for _, p := range v {
			e164s = append(e164s, p.E164)
		}
	}
	phones, err := querycomms.PhonesFromE164s(ctx, txn, e164s)
	if err != nil {
		return nil, fmt.Errorf("contact phones from ids: %w", err)
	}
	phones_by_e164 := make(map[string]modelcomms.Phone, 0)
	for _, p := range phones {
		phones_by_e164[p.E164] = p
	}

	results := make([]types.ContactSimple, len(contact_ids))
	for i, contact := range contacts {
		emails, ok := contact_emails[int64(contact.ID)]
		if !ok {
			return nil, fmt.Errorf("no emails for contact %d", contact.ID)
		}
		cps, ok := contact_phones[int64(contact.ID)]
		if !ok {
			return nil, fmt.Errorf("no phones for contact %d", contact.ID)
		}
		email_string := ""
		if len(emails) > 0 {
			email_string = emails[0].Address
		}
		phone_simple := types.PhoneSimple{}
		if len(cps) > 0 {
			contact_phone := cps[0]
			phone := phones_by_e164[contact_phone.E164]
			phone_simple = types.PhoneSimple{
				CanSMS: phone.CanSms,
				Number: phone.E164,
			}
		}
		results[i] = types.ContactSimple{
			Email: email_string,
			ID:    contact.ID,
			Name:  contact.Name,
			Phone: phone_simple,
		}
	}
	return results, nil
}
