package service

import (
	"context"
	"net/http"
	"strings"

	"cmr-backend/internal/apperr"
	"cmr-backend/internal/store/postgres"
)

type EntryService struct {
	store *postgres.Store
}

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

type ResolveEntryResult struct {
	Tenant struct {
		ID   string `json:"id"`
		Code string `json:"code"`
		Name string `json:"name"`
	} `json:"tenant"`
	Channel struct {
		ID            string  `json:"id"`
		Code          string  `json:"code"`
		Type          string  `json:"type"`
		PlatformAppID *string `json:"platformAppId,omitempty"`
		DisplayName   string  `json:"displayName"`
		Status        string  `json:"status"`
		IsDefault     bool    `json:"isDefault"`
	} `json:"channel"`
}

func NewEntryService(store *postgres.Store) *EntryService {
	return &EntryService{store: store}
}

func (s *EntryService) Resolve(ctx context.Context, input ResolveEntryInput) (*ResolveEntryResult, error) {
	input.ChannelCode = strings.TrimSpace(input.ChannelCode)
	input.ChannelType = strings.TrimSpace(input.ChannelType)
	input.PlatformAppID = strings.TrimSpace(input.PlatformAppID)
	input.TenantCode = strings.TrimSpace(input.TenantCode)

	if input.ChannelCode == "" && input.PlatformAppID == "" {
		return nil, apperr.New(http.StatusBadRequest, "invalid_params", "channelCode or platformAppId is required")
	}

	entry, err := s.store.FindEntryChannel(ctx, postgres.FindEntryChannelParams{
		ChannelCode:   input.ChannelCode,
		ChannelType:   input.ChannelType,
		PlatformAppID: input.PlatformAppID,
		TenantCode:    input.TenantCode,
	})
	if err != nil {
		return nil, err
	}
	if entry == nil {
		return nil, apperr.New(http.StatusNotFound, "entry_channel_not_found", "entry channel not found")
	}

	result := &ResolveEntryResult{}
	result.Tenant.ID = entry.TenantID
	result.Tenant.Code = entry.TenantCode
	result.Tenant.Name = entry.TenantName
	result.Channel.ID = entry.ID
	result.Channel.Code = entry.ChannelCode
	result.Channel.Type = entry.ChannelType
	result.Channel.PlatformAppID = entry.PlatformAppID
	result.Channel.DisplayName = entry.DisplayName
	result.Channel.Status = entry.Status
	result.Channel.IsDefault = entry.IsDefault
	return result, nil
}
