--! Previous: sha1:00899815dc03fa792300ff69dde9d17756448635
--! Hash: sha1:e7ff9a64813ea9e0a701219f6b2ba8ed88dcf240
--! Message: pull command skeleton

--- Runs the full /pull command.
--- Error codes:
---     VGBCG: Bad channel (game). This is not a valid channel to send game commands in.
---     VGBGG: Bad guild (game). This is not a valid guild to send game commands in.
---     VGNYJ: Not yet joined. The Discord user using has not joined the game yet.
---     VGNEC: Not enough currency.
CREATE OR REPLACE FUNCTION Command_Pull(
    IN requestedChannel DiscordChannel.discordId%TYPE,
    IN requestedGuild DiscordChannel.guildId%TYPE,
    IN forId DiscordUser.discordId%TYPE,
    IN newUsername DiscordUser.username%TYPE,
    IN newDiscriminator DiscordUser.discriminator%TYPE,
    IN count INT
)
    RETURNS TABLE
            (
                summonedUnitInstanceId SummonedUnit.instanceId%TYPE,
                summonedUnitId         Unit.id%TYPE,
                summonedUnitName       Unit.name%TYPE,
                summonedUnitSubtitle   Unit.subtitle%TYPE,
                summonedUnitTierName   UnitTier.name%TYPE,
                firstTimePull          BOOLEAN,
                wasAlreadySummoned     BOOLEAN
            )
    STRICT
    VOLATILE
    ROWS 10
AS
$$
DECLARE
    playerId        Player.id%TYPE;
    cost            Player.currency%TYPE;
    oldCurrency     Player.currency%TYPE;
    playerLastDaily Player.lastDaily%TYPE;
BEGIN
    CALL CheckGameCommandIn(requestedChannel, requestedGuild);
    SELECT InvokingPlayer.id, InvokingPlayer.currency, InvokingPlayer.lastDaily
    INTO playerId, oldCurrency, playerLastDaily
    FROM GetInvokingPlayer(forId, newUsername, newDiscriminator) AS InvokingPlayer;
    IF playerId IS NULL THEN
        RAISE EXCEPTION USING
            ERRCODE = 'VGNYJ',
            MESSAGE = 'Not yet joined',
            DETAIL = 'You haven''t joined the game yet, and can''t use this command until you do.',
            HINT = 'Use the /join command to join the game!';
    END IF;
    cost = 10 * count;
    UPDATE Player SET currency = currency - cost WHERE id = playerId AND currency >= cost;
    IF NOT FOUND THEN
        RAISE EXCEPTION USING
            ERRCODE = 'VGNEC',
            MESSAGE = 'Not enough currency',
            DETAIL = format('Pulling %s heroines would cost %s currency, but you only have %s currency.',
                            count, cost, oldCurrency),
            HINT = CASE playerLastDaily IS NULL OR playerLastDaily < NOW() - '1 day'::interval
                       WHEN TRUE THEN 'Try using the /daily command to get some more currency for today!'
                       ELSE format('Wait %s and you can use the /daily command to get some more currency!',
                                   (playerLastDaily + '1 day'::interval) - NOW())
                END;
    END IF;
END;
$$ LANGUAGE 'plpgsql';
