use chrono::Utc;
use uuid::Uuid;

use crate::types::error::{HorizonError, PostgresError, Result};
use crate::types::model::OntologyClass;

use super::PostgresRepository;

impl PostgresRepository {
    /// Delete an ontology class by ID. Returns the number of rows removed.
    pub async fn delete_ontology_class(&self, id: Uuid) -> Result<u64> {
        let result = sqlx::query!(
            "DELETE FROM horizon_public.ontology_class WHERE id = $1",
            id
        )
        .execute(&self.pool)
        .await?;
        Ok(result.rows_affected())
    }

    /// Create an ontology class.
    pub async fn insert_ontology_class(
        &self,
        ontology_class: &OntologyClass,
    ) -> Result<OntologyClass> {
        let now = Utc::now();
        let org = self.organization_id.or(ontology_class.organization_id);
        Ok(sqlx::query_as!(
            OntologyClass,
            r#"
            INSERT INTO horizon_public.ontology_class
                (id, ontology_id, parent_id, name, description,
                 "order", organization_id, relationship_type, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5, $6, $7, $8, $9)
            RETURNING id, created_datetime, modified_datetime, ontology_id,
                      parent_id, name, description, "order",
                      organization_id, relationship_type
            "#,
            ontology_class.id,
            ontology_class.ontology_id,
            ontology_class.parent_id,
            ontology_class.name,
            ontology_class.description,
            ontology_class.order,
            org,
            ontology_class.relationship_type,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }

    /// List all ontology class records.
    pub async fn list_ontology_classes(&self) -> Result<Vec<OntologyClass>> {
        Ok(sqlx::query_as!(
            OntologyClass,
            r#"
            SELECT id, created_datetime, modified_datetime, ontology_id,
                   parent_id, name, description, "order",
                   organization_id, relationship_type
            FROM horizon_public.ontology_class
            "#,
        )
        .fetch_all(&self.pool)
        .await?)
    }

    /// Read an ontology class by ID.
    pub async fn read_ontology_class(&self, id: Uuid) -> Result<Option<OntologyClass>> {
        Ok(sqlx::query_as!(
            OntologyClass,
            r#"
            SELECT id, created_datetime, modified_datetime, ontology_id,
                   parent_id, name, description, "order",
                   organization_id, relationship_type
            FROM horizon_public.ontology_class WHERE id = $1
            "#,
            id,
        )
        .fetch_optional(&self.pool)
        .await?)
    }

    /// Update an existing ontology class by ID.
    ///
    /// Returns `HorizonError::Postgres(PostgresError::NotFound)` if no row
    /// with the given ID exists. Matches Python `BaseRepository.update()`
    /// semantics.
    pub async fn update_ontology_class(
        &self,
        ontology_class: &OntologyClass,
    ) -> Result<OntologyClass> {
        let now = Utc::now();
        let org = self.organization_id.or(ontology_class.organization_id);
        let result = sqlx::query_as!(
            OntologyClass,
            r#"
            UPDATE horizon_public.ontology_class
            SET
                ontology_id = $2,
                parent_id = $3,
                name = $4,
                description = $5,
                "order" = $6,
                organization_id = $7,
                relationship_type = $8,
                modified_datetime = $9
            WHERE id = $1
            RETURNING id, created_datetime, modified_datetime, ontology_id,
                      parent_id, name, description, "order",
                      organization_id, relationship_type
            "#,
            ontology_class.id,
            ontology_class.ontology_id,
            ontology_class.parent_id,
            ontology_class.name,
            ontology_class.description,
            ontology_class.order,
            org,
            ontology_class.relationship_type,
            now,
        )
        .fetch_optional(&self.pool)
        .await?;

        result.ok_or_else(|| {
            HorizonError::Postgres(PostgresError::NotFound {
                entity: "ontology_class".to_owned(),
                id: ontology_class.id.into(),
            })
        })
    }

    /// Insert an ontology class or update it if a row with the same ID
    /// already exists. Sets `modified_datetime` to now and falls back to the
    /// repository's `organization_id` when the model does not provide one.
    pub async fn upsert_ontology_class(
        &self,
        ontology_class: &OntologyClass,
    ) -> Result<OntologyClass> {
        let now = Utc::now();
        let org = self.organization_id.or(ontology_class.organization_id);
        Ok(sqlx::query_as!(
            OntologyClass,
            r#"
            INSERT INTO horizon_public.ontology_class
                (id, ontology_id, parent_id, name, description,
                 "order", organization_id, relationship_type, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5, $6, $7, $8, $9)
            ON CONFLICT (id) DO UPDATE SET
                ontology_id = EXCLUDED.ontology_id, parent_id = EXCLUDED.parent_id,
                name = EXCLUDED.name, description = EXCLUDED.description,
                "order" = EXCLUDED."order", organization_id = EXCLUDED.organization_id,
                relationship_type = EXCLUDED.relationship_type,
                modified_datetime = EXCLUDED.modified_datetime
            RETURNING id, created_datetime, modified_datetime, ontology_id,
                      parent_id, name, description, "order",
                      organization_id, relationship_type
            "#,
            ontology_class.id,
            ontology_class.ontology_id,
            ontology_class.parent_id,
            ontology_class.name,
            ontology_class.description,
            ontology_class.order,
            org,
            ontology_class.relationship_type,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }
}
