#[Copyright 2024 ITwrx.
This file is part of Simple Site Manager.
Simple Site Manager is released under the GNU Affero General Public License 3.0.
See COPYING or <https://www.gnu.org/licenses/> for details.]#

import sqliteral, "../helpers/db"

type
  Session* = object
    sessionId*, csrfToken*: string
    id*, userId*: int
  
proc deleteSessions*() =
  {.gcsafe.}:  
    db1.transaction:
      db1.exec(DeleteSessions)

proc getSessionByCsrfToken*(csrfToken: string): Session =
  {.gcsafe.}:
    var session: Session
    for row in db1.rows(SelectSessionByCsrfToken, csrfToken): 
      session.id = row.getInt(0)
      session.sessionId = row.getString(1)
      session.userId = row.getInt(2)
      session.csrfToken = row.getString(3)
    return session
  
proc createVisitorSession*(visitorSession: Session): int =
  {.gcsafe.}:
    var visitorSessionId: int
    db1.transaction:
      visitorSessionId = db1.insert(InsertVisitorSession, visitorSession.csrfToken)
    return visitorSessionId
