package service

import (
	"context"

	"cloud.google.com/go/bigquery"
	"google.golang.org/api/iterator"

	"data-platform/model"
	"data-platform/pkg/log"
)

/*
	bigquery_legacy.go - 旧版本数据源函数

	此文件包含旧版本的BigQuery数据获取函数，用于从原始单表数据源获取数据。

	用途：
	- 作为新版本数据源的备用方案
	- 在新版本出现问题时可以快速切换回旧版本
	- 通过配置文件 datasource.use_legacy_data_source 来控制是否使用旧版本

	配置切换方法：
	在 config/config-dev.yaml 或 config/config-prod.yaml 中设置：
	datasource:
	  use_legacy_data_source: true  # 使用旧版本
	  use_legacy_data_source: false # 使用新版本 (默认)
*/

// FetchMonthlyOrderInfoLegacy 是旧版本的数据获取函数，使用原始的单表数据源
// 保留此函数作为备用，在新版本出现问题时可以快速切换
func FetchMonthlyOrderInfoLegacy(ctx context.Context, bqSrv *bigquery.Client, first bool) ([]*model.OrgBq, error) {
	log.L(ctx).Info("fetch monthly order info from legacy data source")

	lastMonth := GetLastMonth()

	querySql11 := "SELECT * FROM `gcp-digital-bi.model_of_monthly_cloud_revrec_confirm.dwm_monthly_order_info_calculation11_of_revrec_tenant_v3_view` where bill_month='" + lastMonth + "'"

	records11, err := GetBigqueryDataLegacy(ctx, bqSrv, querySql11)
	if err != nil {
		return nil, err
	}

	uniqueRecords := deDuplicateNewOrdersLegacy(records11)

	log.L(ctx).Info("fetch monthly order info legacy success")

	return uniqueRecords, nil
}

// GetBigqueryDataLegacy 是旧版本的BigQuery数据获取函数
func GetBigqueryDataLegacy(ctx context.Context, bqSrv *bigquery.Client, querySql string) ([]*model.OrgBq, error) {
	log.L(ctx).Infof("get bq data from bigquery (legacy)")

	query := bqSrv.Query(querySql)
	it, err := query.Read(ctx)
	if err != nil {
		log.L(ctx).Errorf("Failed to read query: %v", err)
		return nil, err
	}
	res := make([]*model.OrgBq, 0)

	for {
		var value model.OrgBq
		err := it.Next(&value)
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.L(ctx).Errorf("Failed to read row: %v", err)
			return nil, err
		}

		res = append(res, &value)
	}

	log.L(ctx).Infof("get bq data legacy success")

	return res, nil
}

// deDuplicateNewOrdersLegacy 是旧版本的去重函数
func deDuplicateNewOrdersLegacy(records []*model.OrgBq) []*model.OrgBq {
	duplicateMap := make(map[string]bool)
	var unique []*model.OrgBq

	for _, record := range records {
		if record.NeedNewOrder.StringVal == "yes" {
			key := record.BillMonth.StringVal + "-" + record.AdjustTenantID.StringVal
			if duplicateMap[key] {
				continue
			}
			duplicateMap[key] = true
		}
		unique = append(unique, record)
	}

	return unique
}
