// Package taskcompat owns temporary SQL projections used while old and new
// Task binaries overlap during the canonical-assignee rolling deployment.
//
// The legacy responsibility columns remain the runtime source of truth until
// a later contract release catches assignee_member_id up one final time,
// switches all readers to that column, and removes this package.
package taskcompat

import (
	"fmt"
	"strings"
)

// EffectiveAssigneeRefSQL returns the mixed-version assignee projection for a
// tasks-table alias. The order is the frozen legacy-to-canonical precedence.
func EffectiveAssigneeRefSQL(alias string) string {
	alias = normalizedAlias(alias)
	return fmt.Sprintf(
		"COALESCE(NULLIF(%[1]s.claimed_by_ref, ''), %[1]s.claimed_by_member_id, NULLIF(%[1]s.current_agent_ref, ''), NULLIF(%[1]s.suggested_assignee_ref, ''), NULLIF(%[1]s.reviewer_ref, ''))",
		alias,
	)
}

// EffectiveAssignedAtSQL returns the best available timestamp for the
// mixed-version projection. Legacy claims have claimed_at. The other legacy
// writers only touch updated_at, so a ref which differs from the canonical
// mirror uses updated_at. A synchronized mirror keeps its stable assigned_at.
func EffectiveAssignedAtSQL(alias string) string {
	alias = normalizedAlias(alias)
	effectiveRef := EffectiveAssigneeRefSQL(alias)
	claimedRef := fmt.Sprintf(
		"COALESCE(NULLIF(%[1]s.claimed_by_ref, ''), %[1]s.claimed_by_member_id)",
		alias,
	)
	return fmt.Sprintf(`CASE
        WHEN %[1]s IS NULL THEN NULL
        WHEN %[2]s IS NOT NULL THEN COALESCE(%[3]s.claimed_at, %[3]s.assigned_at, %[3]s.updated_at, %[3]s.created_at)
        WHEN %[1]s <> COALESCE(%[3]s.assignee_member_id, '') THEN COALESCE(%[3]s.updated_at, %[3]s.assigned_at, %[3]s.created_at)
        ELSE COALESCE(%[3]s.assigned_at, %[3]s.updated_at, %[3]s.created_at)
    END`, effectiveRef, claimedRef, alias)
}

func normalizedAlias(alias string) string {
	alias = strings.TrimSpace(alias)
	if alias == "" {
		return "t"
	}
	return alias
}
