package comms

import (
	"context"
	"errors"
	"fmt"

	//"github.com/Gleipnir-Technology/bob"
	"source.gleipnir.technology/Gleipnir/nidus-sync/db"
	//"source.gleipnir.technology/Gleipnir/nidus-sync/db/gen/nidus-sync/public/enum"
	"github.com/Gleipnir-Technology/jet/postgres"
	"source.gleipnir.technology/Gleipnir/nidus-sync/db/gen/nidus-sync/comms/model"
	"source.gleipnir.technology/Gleipnir/nidus-sync/db/gen/nidus-sync/comms/table"
)

func ContactInsert(ctx context.Context, txn db.Ex, m model.Contact) (model.Contact, error) {
	statement := table.Contact.INSERT(table.Contact.MutableColumns).
		MODEL(m).
		RETURNING(table.Contact.AllColumns)
	return db.ExecuteOneTx[model.Contact](ctx, txn, statement)
}

func ContactEmptyForOrganization(ctx context.Context, txn db.Ex, org_id int64) (*model.Contact, error) {
	statement := table.Contact.SELECT(
		table.Contact.AllColumns,
	).FROM(table.Contact).
		WHERE(
			postgres.AND(
				table.Contact.OrganizationID.EQ(postgres.Int(org_id)),
				table.Contact.Name.EQ(postgres.String("")),
				postgres.NOT(
					postgres.EXISTS(
						postgres.SELECT(
							postgres.RawInt("1"),
						).FROM(table.ContactEmail).
							WHERE(table.ContactEmail.ContactID.EQ(table.Contact.ID)),
					)),
				postgres.NOT(
					postgres.EXISTS(
						postgres.SELECT(
							postgres.RawInt("1"),
						).FROM(table.ContactPhone).
							WHERE(table.ContactPhone.ContactID.EQ(table.Contact.ID)),
					)),
			),
		)
	row, err := db.ExecuteOne[model.Contact](ctx, statement)
	if err != nil {
		if errors.Is(err, db.ErrNoRows) {
			return nil, nil
		}
		return nil, fmt.Errorf("query contact: %w", err)
	}
	return &row, nil
}
func ContactFromEmail(ctx context.Context, txn db.Ex, email string) (*model.Contact, error) {
	statement := table.Contact.SELECT(
		table.Contact.AllColumns,
	).FROM(
		table.Contact.INNER_JOIN(
			table.ContactEmail,
			table.ContactEmail.ContactID.EQ(table.Contact.ID),
		),
	).WHERE(table.ContactEmail.Address.EQ(postgres.String(email)))
	row, err := db.ExecuteOne[model.Contact](ctx, statement)
	if err != nil {
		if errors.Is(err, db.ErrNoRows) {
			return nil, nil
		}
		return nil, fmt.Errorf("query contact from email '%s': %w", email, err)
	}
	return &row, nil
}
func ContactFromID(ctx context.Context, txn db.Ex, id int64) (model.Contact, error) {
	statement := table.Contact.SELECT(
		table.Contact.AllColumns,
	).FROM(table.Contact).
		WHERE(table.Contact.ID.EQ(postgres.Int(id)))
	return db.ExecuteOne[model.Contact](ctx, statement)
}
func ContactsFromIDs(ctx context.Context, txn db.Ex, contact_ids []int64) ([]model.Contact, error) {
	if len(contact_ids) == 0 {
		return []model.Contact{}, nil
	}
	sql_ids := make([]postgres.Expression, len(contact_ids))
	for i, contact_id := range contact_ids {
		sql_ids[i] = postgres.Int(contact_id)
	}
	statement := table.Contact.SELECT(
		table.Contact.AllColumns,
	).FROM(table.Contact).
		WHERE(table.Contact.ID.IN(sql_ids...))
	return db.ExecuteManyTx[model.Contact](ctx, txn, statement)
}
func ContactFromPhone(ctx context.Context, txn db.Ex, e164 string) (*model.Contact, error) {
	statement := table.Contact.SELECT(
		table.Contact.AllColumns,
	).FROM(
		table.Contact.INNER_JOIN(
			table.ContactPhone,
			table.ContactPhone.ContactID.EQ(table.Contact.ID),
		),
	).WHERE(table.ContactPhone.E164.EQ(postgres.String(e164)))
	row, err := db.ExecuteOne[model.Contact](ctx, statement)
	if err != nil {
		if errors.Is(err, db.ErrNoRows) {
			return nil, nil
		}
		return nil, fmt.Errorf("query contact from phone '%s': %w", e164, err)
	}
	return &row, nil
}
func ContactUpdateName(ctx context.Context, txn db.Ex, id int64, name string) error {
	statement := table.Contact.UPDATE().
		SET(
			table.Contact.Name.SET(postgres.String(name)),
		).
		WHERE(table.Contact.ID.EQ(postgres.Int(id)))
	return db.ExecuteNoneTx(ctx, txn, statement)
}

func ContactsFromOrganizationID(ctx context.Context, txn db.Ex, org_id int64) ([]model.Contact, error) {
	statement := table.Contact.SELECT(
		table.Contact.AllColumns,
	).FROM(table.Contact).
		WHERE(table.Contact.OrganizationID.EQ(postgres.Int(org_id)))
	return db.ExecuteManyTx[model.Contact](ctx, txn, statement)
}
