package lib

import "fmt"

func GetOrCreateUserWithGuild(discordID string, username string, guildID string) (int, error) {
	var userID int

	tx, err := DBClient.Begin()
	if err != nil {
		return 0, fmt.Errorf("failed to start transaction: %w", err)
	}
	defer tx.Rollback()

	// First get or create the user
	err = tx.QueryRow(`
        INSERT INTO users (discord_id, username)
        VALUES (?, ?)
        ON CONFLICT (discord_id)
        DO UPDATE SET username = excluded.username
        RETURNING id`,
		discordID, username).Scan(&userID)

	if err != nil {
		return 0, fmt.Errorf("failed to get or create user: %w", err)
	}

	// Then ensure guild profile exists for this user
	_, err = tx.Exec(`
        INSERT INTO guild_profiles (user_id, guild_id, currency_balance, message_count)
        VALUES (?, ?, 0, 0)
        ON CONFLICT (user_id, guild_id) DO NOTHING`,
		userID, guildID)

	if err != nil {
		return 0, fmt.Errorf("failed to create guild profile: %w", err)
	}

	if err := tx.Commit(); err != nil {
		return 0, fmt.Errorf("failed to commit transaction: %w", err)
	}

	return userID, nil
}
