package sqlite

import (
	"context"
	"fmt"
	"strings"
)

type LogicalGroupRouteModel struct {
	ID          int64
	RouteID     string
	PublicModel string
	ShadowModel string
	Status      string
	CreatedAt   string
	UpdatedAt   string
}

type LogicalGroupRouteModelsRepo struct {
	db execQuerier
}

func newLogicalGroupRouteModelsRepo(db execQuerier) *LogicalGroupRouteModelsRepo {
	return &LogicalGroupRouteModelsRepo{db: db}
}

func (r *LogicalGroupRouteModelsRepo) Create(ctx context.Context, model LogicalGroupRouteModel) (int64, error) {
	model, err := normalizeLogicalGroupRouteModel(model)
	if err != nil {
		return 0, err
	}

	result, err := r.db.ExecContext(
		ctx,
		`INSERT INTO logical_group_route_models (route_id, public_model, shadow_model, status)
		VALUES (?, ?, ?, ?)`,
		model.RouteID,
		model.PublicModel,
		model.ShadowModel,
		model.Status,
	)
	if err != nil {
		return 0, fmt.Errorf("insert logical group route model %q/%q: %w", model.RouteID, model.PublicModel, err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		return 0, fmt.Errorf("read inserted logical group route model id for %q/%q: %w", model.RouteID, model.PublicModel, err)
	}
	return id, nil
}

func (r *LogicalGroupRouteModelsRepo) ListByRouteID(ctx context.Context, routeID string) ([]LogicalGroupRouteModel, error) {
	routeID = strings.TrimSpace(routeID)
	if routeID == "" {
		return nil, fmt.Errorf("route_id is required")
	}

	rows, err := r.db.QueryContext(
		ctx,
		`SELECT id, route_id, public_model, shadow_model, status, created_at, updated_at
		FROM logical_group_route_models
		WHERE route_id = ?
		ORDER BY id ASC`,
		routeID,
	)
	if err != nil {
		return nil, fmt.Errorf("list logical group route models for %q: %w", routeID, err)
	}
	defer rows.Close()

	models := make([]LogicalGroupRouteModel, 0)
	for rows.Next() {
		var model LogicalGroupRouteModel
		if err := rows.Scan(
			&model.ID,
			&model.RouteID,
			&model.PublicModel,
			&model.ShadowModel,
			&model.Status,
			&model.CreatedAt,
			&model.UpdatedAt,
		); err != nil {
			return nil, fmt.Errorf("scan logical group route model: %w", err)
		}
		models = append(models, model)
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("iterate logical group route models for %q: %w", routeID, err)
	}
	return models, nil
}

func normalizeLogicalGroupRouteModel(model LogicalGroupRouteModel) (LogicalGroupRouteModel, error) {
	model.RouteID = strings.TrimSpace(model.RouteID)
	model.PublicModel = strings.TrimSpace(model.PublicModel)
	model.ShadowModel = strings.TrimSpace(model.ShadowModel)
	model.Status = strings.TrimSpace(model.Status)

	switch {
	case model.RouteID == "":
		return LogicalGroupRouteModel{}, fmt.Errorf("route_id is required")
	case model.PublicModel == "":
		return LogicalGroupRouteModel{}, fmt.Errorf("public_model is required")
	}
	if model.ShadowModel == "" {
		model.ShadowModel = model.PublicModel
	}
	if model.Status == "" {
		model.Status = "active"
	}
	return model, nil
}
