package public

import (
	"context"
	"errors"
	"fmt"

	"github.com/Gleipnir-Technology/jet/postgres"
	"source.gleipnir.technology/Gleipnir/nidus-sync/db"
	"source.gleipnir.technology/Gleipnir/nidus-sync/db/gen/nidus-sync/public/table"
	"source.gleipnir.technology/Gleipnir/nidus-sync/platform/types"
)

func mailerBaseQuery() postgres.SelectStatement {
	return table.ComplianceReportRequest.SELECT(
		table.Address.AllColumns,
		table.ComplianceReportRequest.AllColumns,
	).FROM(
		table.ComplianceReportRequest,
	).FROM(
		table.ComplianceReportRequest.INNER_JOIN(
			table.ComplianceReportRequestMailer,
			table.ComplianceReportRequestMailer.ComplianceReportRequestID.EQ(
				table.ComplianceReportRequest.ID),
		),
	).FROM(
		table.ComplianceReportRequest.INNER_JOIN(
			table.Lead,
			table.Lead.ID.EQ(
				table.ComplianceReportRequest.LeadID,
			),
		),
	).FROM(
		table.Lead.INNER_JOIN(
			table.Site,
			table.Site.ID.EQ(
				table.Lead.SiteID,
			),
		),
	).FROM(
		table.Site.INNER_JOIN(
			table.Address,
			table.Address.ID.EQ(
				table.Site.AddressID,
			),
		),
	)
}

// func MailerFromPublicID(ctx context.Context, txn db.Ex, org_id int64, id int64) (*types.Mailer, error) {
func MailerFromID(ctx context.Context, txn db.Ex, org_id int64, id int64) (*types.Mailer, error) {
	statement := mailerBaseQuery().WHERE(
		table.ComplianceReportRequest.ID.EQ(postgres.Int(id)).AND(
			table.Site.OrganizationID.EQ(postgres.Int(org_id))),
	)
	row, err := db.ExecuteOneTx[types.Mailer](ctx, txn, statement)
	if err != nil {
		if errors.Is(err, db.ErrNoRows) {
			return nil, nil
		}
		return nil, fmt.Errorf("query: %w", err)
	}
	return &row, nil
}
func MailersFromOrganizationID(ctx context.Context, txn db.Ex, org_id int64, limit int64) ([]types.Mailer, error) {
	statement := mailerBaseQuery().WHERE(
		table.Site.OrganizationID.EQ(postgres.Int(org_id)),
	).ORDER_BY(
		table.ComplianceReportRequest.Created,
	).LIMIT(limit)
	return db.ExecuteManyTx[types.Mailer](ctx, txn, statement)
}
