package postgres

import (
	"context"
	"errors"
	"fmt"

	"github.com/jackc/pgx/v5"
)

type EntryChannel struct {
	ID            string
	ChannelCode   string
	ChannelType   string
	PlatformAppID *string
	DisplayName   string
	Status        string
	IsDefault     bool
	TenantID      string
	TenantCode    string
	TenantName    string
}

type FindEntryChannelParams struct {
	ChannelCode   string
	ChannelType   string
	PlatformAppID string
	TenantCode    string
}

func (s *Store) FindEntryChannel(ctx context.Context, params FindEntryChannelParams) (*EntryChannel, error) {
	row := s.pool.QueryRow(ctx, `
		SELECT
			ec.id,
			ec.channel_code,
			ec.channel_type,
			ec.platform_app_id,
			ec.display_name,
			ec.status,
			ec.is_default,
			t.id,
			t.tenant_code,
			t.name
		FROM entry_channels ec
		JOIN tenants t ON t.id = ec.tenant_id
		WHERE ($1 = '' OR ec.channel_code = $1)
		  AND ($2 = '' OR ec.channel_type = $2)
		  AND ($3 = '' OR COALESCE(ec.platform_app_id, '') = $3)
		  AND ($4 = '' OR t.tenant_code = $4)
		ORDER BY ec.is_default DESC, ec.created_at ASC
		LIMIT 1
	`, params.ChannelCode, params.ChannelType, params.PlatformAppID, params.TenantCode)

	var entry EntryChannel
	err := row.Scan(
		&entry.ID,
		&entry.ChannelCode,
		&entry.ChannelType,
		&entry.PlatformAppID,
		&entry.DisplayName,
		&entry.Status,
		&entry.IsDefault,
		&entry.TenantID,
		&entry.TenantCode,
		&entry.TenantName,
	)
	if errors.Is(err, pgx.ErrNoRows) {
		return nil, nil
	}
	if err != nil {
		return nil, fmt.Errorf("find entry channel: %w", err)
	}
	return &entry, nil
}
