package store

import (
	"context"
	"errors"
	"strings"
	"time"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/identity"
	"github.com/google/uuid"
	"github.com/jackc/pgx/v5"
)

type OIDCTenantBindingSyncTarget struct {
	ID               string
	ExternalTenantID string
	ETag             string
	FailureCount     int
}

type OIDCTenantBindingContext struct {
	ID                string
	AccessStatus      string
	MetadataStatus    string
	DisplayName       string
	Slug              string
	Version           string
	ETag              string
	MetadataUpdatedAt time.Time
	NextSyncAt        time.Time
}

func (s *Store) DueOIDCTenantBindingSyncs(ctx context.Context, issuer, applicationID string, limit int) ([]OIDCTenantBindingSyncTarget, error) {
	if limit <= 0 || limit > 100 {
		limit = 50
	}
	rows, err := s.pool.Query(ctx, `SELECT id::text,external_tenant_id,COALESCE(metadata_etag,''),sync_failure_count
		FROM gateway_oidc_tenant_bindings
		WHERE issuer=$1 AND application_id=$2 AND access_status='active' AND next_sync_at <= now()
		ORDER BY next_sync_at,id
		LIMIT $3`, strings.TrimRight(strings.TrimSpace(issuer), "/"), strings.TrimSpace(applicationID), limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	result := make([]OIDCTenantBindingSyncTarget, 0)
	for rows.Next() {
		var item OIDCTenantBindingSyncTarget
		if err := rows.Scan(&item.ID, &item.ExternalTenantID, &item.ETag, &item.FailureCount); err != nil {
			return nil, err
		}
		result = append(result, item)
	}
	return result, rows.Err()
}

func (s *Store) OIDCTenantBindingContext(ctx context.Context, issuer, applicationID, tenantID string) (OIDCTenantBindingContext, error) {
	var item OIDCTenantBindingContext
	err := s.pool.QueryRow(ctx, `SELECT id::text,access_status,metadata_status,COALESCE(display_name,''),
		COALESCE(slug,''),COALESCE(metadata_version,''),COALESCE(metadata_etag,''),
		COALESCE(metadata_updated_at,'epoch'::timestamptz),next_sync_at
		FROM gateway_oidc_tenant_bindings
		WHERE issuer=$1 AND application_id=$2 AND external_tenant_id=$3`,
		strings.TrimRight(strings.TrimSpace(issuer), "/"), strings.TrimSpace(applicationID), strings.TrimSpace(tenantID),
	).Scan(&item.ID, &item.AccessStatus, &item.MetadataStatus, &item.DisplayName, &item.Slug,
		&item.Version, &item.ETag, &item.MetadataUpdatedAt, &item.NextSyncAt)
	if errors.Is(err, pgx.ErrNoRows) {
		return OIDCTenantBindingContext{}, ErrOIDCTenantUnavailable
	}
	return item, err
}

func (s *Store) ApplyOIDCTenantBindingSync(ctx context.Context, bindingID string, tenant identity.TenantContext, unchanged bool, now time.Time) error {
	if uuid.Validate(bindingID) != nil {
		return errors.New("OIDC tenant binding id is invalid")
	}
	tx, err := s.pool.Begin(ctx)
	if err != nil {
		return err
	}
	defer rollbackTransaction(tx)
	if unchanged {
		tag, err := tx.Exec(ctx, `UPDATE gateway_oidc_tenant_bindings
			SET last_sync_at=$2::timestamptz,next_sync_at=$2::timestamptz+interval '15 minutes',sync_failure_count=0,
			    last_error_category=NULL,updated_at=now()
			WHERE id=$1::uuid AND access_status='active'`, bindingID, now)
		if err != nil {
			return err
		}
		if tag.RowsAffected() == 0 {
			return ErrOIDCTenantUnavailable
		}
		return tx.Commit(ctx)
	}
	if !tenant.Active() || strings.TrimSpace(tenant.DisplayName) == "" || strings.TrimSpace(tenant.Slug) == "" {
		return errors.New("OIDC tenant context is inactive or incomplete")
	}
	var gatewayTenantID string
	err = tx.QueryRow(ctx, `UPDATE gateway_oidc_tenant_bindings
		SET metadata_status='synced',display_name=$2,slug=$3,metadata_version=$4,metadata_etag=NULLIF($5,''),
		    metadata_updated_at=$6,last_sync_at=$7::timestamptz,
		    next_sync_at=$7::timestamptz+interval '15 minutes',
		    sync_failure_count=0,last_error_category=NULL,updated_at=now()
		WHERE id=$1::uuid AND access_status='active'
		RETURNING gateway_tenant_id::text`,
		bindingID, tenant.DisplayName, tenant.Slug, tenant.Version, tenant.ETag, tenant.UpdatedAt, now,
	).Scan(&gatewayTenantID)
	if errors.Is(err, pgx.ErrNoRows) {
		return ErrOIDCTenantUnavailable
	}
	if err != nil {
		return err
	}
	if _, err := tx.Exec(ctx, `UPDATE gateway_tenants
		SET name=$2,synced_at=$3,source_updated_at=$4,updated_at=now()
		WHERE id=$1::uuid AND source='oidc_v2' AND status='active' AND deleted_at IS NULL`,
		gatewayTenantID, tenant.DisplayName, now, tenant.UpdatedAt,
	); err != nil {
		return err
	}
	return tx.Commit(ctx)
}

func (s *Store) RejectOIDCTenantBinding(ctx context.Context, bindingID, category string, now time.Time) error {
	if uuid.Validate(bindingID) != nil {
		return errors.New("OIDC tenant binding id is invalid")
	}
	tx, err := s.pool.Begin(ctx)
	if err != nil {
		return err
	}
	defer rollbackTransaction(tx)
	tag, err := tx.Exec(ctx, `UPDATE gateway_oidc_tenant_bindings
		SET access_status='disabled',metadata_status='rejected',last_sync_at=$2::timestamptz,
		    next_sync_at=$2::timestamptz+interval '15 minutes',
		    last_error_category=$3,updated_at=now()
		WHERE id=$1::uuid`, bindingID, now, limitOIDCTenantContextCategory(category))
	if err != nil {
		return err
	}
	if tag.RowsAffected() == 0 {
		return ErrOIDCTenantUnavailable
	}
	if _, err := tx.Exec(ctx, `DELETE FROM gateway_oidc_sessions session
		USING gateway_oidc_user_bindings user_binding
		WHERE session.oidc_user_binding_id=user_binding.id AND user_binding.tenant_binding_id=$1::uuid`,
		bindingID,
	); err != nil {
		return err
	}
	return tx.Commit(ctx)
}

func (s *Store) FailOIDCTenantBindingSync(ctx context.Context, bindingID, category string, next time.Time) error {
	if uuid.Validate(bindingID) != nil {
		return errors.New("OIDC tenant binding id is invalid")
	}
	tag, err := s.pool.Exec(ctx, `UPDATE gateway_oidc_tenant_bindings
		SET sync_failure_count=sync_failure_count+1,next_sync_at=$2,last_error_category=$3,updated_at=now()
		WHERE id=$1::uuid AND access_status='active'`, bindingID, next, limitOIDCTenantContextCategory(category))
	if err != nil {
		return err
	}
	if tag.RowsAffected() == 0 {
		return ErrOIDCTenantUnavailable
	}
	return nil
}

func limitOIDCTenantContextCategory(value string) string {
	value = strings.TrimSpace(value)
	if len(value) > 64 {
		return value[:64]
	}
	return value
}
