//! {{RESOURCE_NAME_PASCAL}} repository
//!
//! Generated by: keg gen api {{RESOURCE_NAME}}
//!
//! Provides data access operations. Uses sqlx with compile-time query checking.

use crate::{{{PROJECT_NAME_SNAKE}}}::internal::model::entity::{{RESOURCE_NAME}};
use anyhow::Result;
use sqlx::PgPool;

/// Repository for {{RESOURCE_NAME}} entities
#[derive(Clone)]
pub struct {{RESOURCE_NAME_PASCAL}}Repository {
    pool: PgPool,
}

impl {{RESOURCE_NAME_PASCAL}}Repository {
    /// Create a new repository instance
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }

    /// List all {{RESOURCE_NAME}} records with pagination
    pub async fn list(&self, limit: i64, offset: i64) -> Result<Vec<{{RESOURCE_NAME_PASCAL}}>> {
        let rows = sqlx::query_as::<_, {{RESOURCE_NAME_PASCAL}}>(
            "SELECT id, name, created_at, updated_at FROM {{RESOURCE_NAME}}
             ORDER BY created_at DESC LIMIT $1 OFFSET $2",
        )
        .bind(limit)
        .bind(offset)
        .fetch_all(&self.pool)
        .await?;
        Ok(rows)
    }

    /// Find a {{RESOURCE_NAME}} by ID
    pub async fn find_by_id(&self, id: uuid::Uuid) -> Result<Option<{{RESOURCE_NAME_PASCAL}}>> {
        let row = sqlx::query_as::<_, {{RESOURCE_NAME_PASCAL}}>(
            "SELECT id, name, created_at, updated_at FROM {{RESOURCE_NAME}} WHERE id = $1",
        )
        .bind(id)
        .fetch_optional(&self.pool)
        .await?;
        Ok(row)
    }

    /// Insert a new {{RESOURCE_NAME}}
    pub async fn insert(&self, entity: &{{RESOURCE_NAME_PASCAL}}) -> Result<()> {
        sqlx::query(
            "INSERT INTO {{RESOURCE_NAME}} (id, name, created_at, updated_at)
             VALUES ($1, $2, $3, $4)",
        )
        .bind(entity.id)
        .bind(&entity.name)
        .bind(entity.created_at)
        .bind(entity.updated_at)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    /// Update an existing {{RESOURCE_NAME}}
    pub async fn update(&self, entity: &{{RESOURCE_NAME_PASCAL}}) -> Result<()> {
        sqlx::query(
            "UPDATE {{RESOURCE_NAME}}
             SET name = $2, updated_at = $3
             WHERE id = $1",
        )
        .bind(entity.id)
        .bind(&entity.name)
        .bind(entity.updated_at)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    /// Delete a {{RESOURCE_NAME}} by ID
    pub async fn delete(&self, id: uuid::Uuid) -> Result<()> {
        sqlx::query("DELETE FROM {{RESOURCE_NAME}} WHERE id = $1")
            .bind(id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }
}