package schema_utils

import (
	"context"

	"cloud.google.com/go/bigquery"
)

var BigQueryTypeMaping = map[bigquery.FieldType]string{
	bigquery.StringFieldType: "text",
}

type BigqueryDB struct {
	client *bigquery.Client
}

func NewBigqueryDB(client *bigquery.Client) *BigqueryDB {
	return &BigqueryDB{client: client}
}

func (db *BigqueryDB) FetchTableInfo(ctx context.Context, projectID, datasetID, tableID string) (*TableInfo, error) {
	schema := &TableInfo{
		DB:      datasetID,
		Table:   tableID,
		Columns: make(map[string]*ColumnInfo),
	}

	meta, err := db.client.Dataset(datasetID).Table(tableID).Metadata(ctx)
	if err != nil {
		return nil, err
	}

	for _, info := range meta.Schema {
		typ, ok := BigQueryTypeMaping[info.Type]
		if !ok {
			typ = string(info.Type)
		}
		schema.Columns[info.Name] = &ColumnInfo{
			Name: info.Name,
			Typ:  typ,
		}
	}

	return schema, nil
}
