package db

import (
	"fmt"

	cortypes "gitlink.org.cn/cloudream/jcs-pub/coordinator/types"
)

type LocationDB struct {
	*DB
}

func (db *DB) Location() *LocationDB {
	return &LocationDB{DB: db}
}

func (*LocationDB) GetByID(ctx SQLContext, id int64) (cortypes.Location, error) {
	var ret cortypes.Location
	err := ctx.First(&ret, id).Error
	return ret, err
}

func (db *LocationDB) FindLocationByExternalIP(ctx SQLContext, ip string) (cortypes.Location, error) {
	var locID int64
	err := ctx.Table("Hub").Select("LocationID").Where("ExternalIP = ?", ip).Scan(&locID).Error
	if err != nil {
		return cortypes.Location{}, fmt.Errorf("finding hub by external ip: %w", err)
	}

	loc, err := db.GetByID(ctx, locID)
	if err != nil {
		return cortypes.Location{}, fmt.Errorf("getting location by id: %w", err)
	}

	return loc, nil
}
