use uuid::Uuid; use chrono::{DateTime, Utc}; use sqlx::{PgPool, FromRow}; use serde::Serialize; use crate::http_error::HttpError; #[derive(Serialize, FromRow)] pub struct Turn { pub id: Uuid, pub session_id: Uuid, pub tokens_used: i32, pub user_text: String, pub llm_text: String, pub created_at: DateTime } impl Turn { pub fn new( session_id: Uuid, input_tokens: i32, output_tokens: i32, user_text: String, llm_text: String ) -> Self { Self { id: Uuid::now_v7(), session_id: session_id, tokens_used: input_tokens + (output_tokens * 2), user_text: user_text, llm_text: llm_text, created_at: Utc::now() } } pub async fn insert(&self, db: &PgPool) -> Result<(), HttpError> { sqlx::query( "INSERT INTO turns(id, session_id, tokens_used, user_text, llm_text, created_at) VALUES($1, $2, $3, $4, $5, $6)" ) .bind(&self.id) .bind(&self.session_id) .bind(&self.tokens_used) .bind(&self.user_text) .bind(&self.llm_text) .bind(&self.created_at) .execute(db) .await?; Ok(()) } pub async fn find_by_session(db: &PgPool, session_id: Uuid) -> Result, HttpError> { let turns = sqlx::query_as::<_, Turn>( "SELECT * FROM turns WHERE session_id = $1 ORDER BY created_at ASC" ) .bind(session_id) .fetch_all(db) .await?; Ok(turns) } }