package controller

import (
    "arimelody-web/model"
    "math/rand"
    "strings"
    "time"

    "github.com/jmoiron/sqlx"
)

var inviteChars = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

func GetInvite(db *sqlx.DB, code string) (*model.Invite, error) {
    invite := model.Invite{}

    err := db.Get(&invite, "SELECT * FROM invite WHERE code=$1", code)
    if err != nil {
        if strings.Contains(err.Error(), "no rows") {
            return nil, nil
        }
        return nil, err
    }

    return &invite, nil
}

func CreateInvite(db *sqlx.DB, length int, lifetime time.Duration) (*model.Invite, error) {
    invite := model.Invite{
        CreatedAt: time.Now(),
        ExpiresAt: time.Now().Add(lifetime),
    }
    
    code := []byte{}
    for i := 0; i < length; i++ {
        code = append(code, inviteChars[rand.Intn(len(inviteChars) - 1)])
    }
    invite.Code = string(code)

    _, err := db.Exec(
        "INSERT INTO invite (code, created_at, expires_at) " +
        "VALUES ($1, $2, $3)",
        invite.Code,
        invite.CreatedAt,
        invite.ExpiresAt,
    )
    if err != nil {
        return nil, err
    }

    return &invite, nil
}

func DeleteInvite(db *sqlx.DB, code string) error {
    _, err := db.Exec("DELETE FROM invite WHERE code=$1", code)
    return err
}

func DeleteAllInvites(db *sqlx.DB) error {
    _, err := db.Exec("DELETE FROM invite")
    return err
}

func DeleteExpiredInvites(db *sqlx.DB) error {
    _, err := db.Exec("DELETE FROM invite WHERE expires_at<current_timestamp")
    return err
}
