use super::Result;
use sqlx::{query, query_as, PgPool};

#[derive(Clone, Debug)]
pub struct Area {
    pub id: i32,
    pub name: String,
}

impl Area {
    pub async fn create(pool: &PgPool, name: &str) -> Result<i32> {
        let result = query!("INSERT INTO area (name) VALUES ($1) RETURNING id;", name)
            .fetch_one(pool)
            .await?;

        Ok(result.id)
    }

    pub async fn read_by_id(pool: &PgPool, id: i32) -> Result<Option<Area>> {
        let record = query_as!(Area, "SELECT * FROM area WHERE id = $1", id)
            .fetch_optional(pool)
            .await?;

        Ok(record)
    }

    pub async fn read_all(pool: &PgPool) -> Result<Vec<Area>> {
        let records = query_as!(Area, "SELECT * FROM area ORDER by id")
            .fetch_all(pool)
            .await?;

        Ok(records)
    }

    pub async fn update(pool: &PgPool, id: i32, name: &str) -> Result<()> {
        query!("UPDATE area SET name = $1 WHERE id = $2;", name, id)
            .execute(pool)
            .await?;

        Ok(())
    }

    pub async fn delete(pool: &PgPool, id: i32) -> Result<()> {
        sqlx::query!("DELETE FROM area WHERE id = $1;", id)
            .execute(pool)
            .await?;

        Ok(())
    }
}
