package platform

import (
	"context"
	"fmt"
	"strconv"

	"source.gleipnir.technology/Gleipnir/nidus-sync/db"
	querypublic "source.gleipnir.technology/Gleipnir/nidus-sync/db/query/public"
	querypublicreport "source.gleipnir.technology/Gleipnir/nidus-sync/db/query/publicreport"
	"source.gleipnir.technology/Gleipnir/nidus-sync/lint"
	"source.gleipnir.technology/Gleipnir/nidus-sync/platform/event"
	"source.gleipnir.technology/Gleipnir/nidus-sync/platform/publicreport"
	"source.gleipnir.technology/Gleipnir/nidus-sync/platform/types"
	//"github.com/rs/zerolog/log"
)

type PublicreportNotification struct {
	Consent      bool
	Email        string
	Name         string
	Notification bool
	Phone        *types.E164
	PhoneCanSms  bool
	ReportID     string
	Subscription bool
}

func PublicreportNotificationCreate(ctx context.Context, pn PublicreportNotification) error {
	txn, err := db.BeginTxn(ctx)
	if err != nil {
		return fmt.Errorf("begin txn: %w", err)
	}
	defer lint.LogOnErrRollback(txn.Rollback, ctx, "rollback")

	report, err := querypublicreport.ReportFromPublicID(ctx, txn, pn.ReportID)
	if err != nil {
		return fmt.Errorf("find report '%s': %w", pn.ReportID, err)
	}
	if report == nil {
		return fmt.Errorf("no such report '%s'", pn.ReportID)
	}

	contact, err := publicreport.SaveReporter(ctx, txn, *report, pn.Name, pn.Email, pn.Phone, pn.PhoneCanSms)
	if err != nil {
		return fmt.Errorf("save reporter: %w", err)
	}
	if pn.Email != "" {
		if pn.Subscription {
			err = publicreport.RegisterSubscriptionEmail(ctx, txn, contact, pn.Email)
			if err != nil {
				return fmt.Errorf("register subscription email: %w", err)
			}
		}
		if pn.Notification {
			err = publicreport.RegisterNotificationEmail(ctx, txn, *report, contact, pn.Email)
			if err != nil {
				return fmt.Errorf("register notification email: %w", err)
			}
		}
	}
	if pn.Phone != nil {
		if pn.Subscription {
			err = publicreport.RegisterSubscriptionPhone(ctx, txn, contact, *pn.Phone)
			if err != nil {
				return fmt.Errorf("register subscription phone: %w", err)
			}
		}
		if pn.Notification {
			err = publicreport.RegisterNotificationPhone(ctx, txn, *report, contact, *pn.Phone)
			if err != nil {
				return fmt.Errorf("register notification phone: %w", err)
			}
		}
	}
	if err := txn.Commit(ctx); err != nil {
		return fmt.Errorf("commit: %w", err)
	}
	event.Updated(event.TypeRMOPublicReport, report.OrganizationID, pn.ReportID)
	comm, err := querypublic.CommunicationFromReportID(ctx, db.PGInstance.PGXPool, int64(report.ID))
	if err != nil {
		return fmt.Errorf("communication from report ID %d: %w", report.ID, err)
	}
	event.Updated(event.TypeCommunication, report.OrganizationID, strconv.Itoa(int(comm.ID)))
	return nil
}
