use chrono::Utc;
use tracing::debug;
use uuid::Uuid;

use crate::postgres::retry::{RetryPolicy, retry};
use crate::types::error::{HorizonError, PostgresError, Result};
use crate::types::model::Mission;

use super::PostgresRepository;

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

    /// Create a new mission.
    pub async fn insert_mission(&self, mission: &Mission) -> Result<Mission> {
        let now = Utc::now();
        let org = self.organization_id.or(mission.organization_id);
        let pos_x = mission.position.map(|pos| pos.0);
        let pos_y = mission.position.map(|pos| pos.1);
        let result = sqlx::query_as!(
            Mission,
            r#"
            INSERT INTO horizon_public.mission
                (id, name, start_datetime, end_datetime, free_text,
                 organization_id, position, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5, $6,
                    CASE WHEN $7::float8 IS NOT NULL THEN point($7, $8::float8) END, $9)
            RETURNING
                id, created_datetime, modified_datetime, name,
                start_datetime, end_datetime,
                position as "position: _", free_text, organization_id
            "#,
            mission.id,
            mission.name,
            mission.start_datetime,
            mission.end_datetime,
            mission.free_text,
            org,
            pos_x,
            pos_y,
            now,
        )
        .fetch_one(&self.pool)
        .await?;
        debug!(
            mission_id = ?result.id,
            mission_name = ?result.name,
            "insert_mission"
        );
        Ok(result)
    }

    /// List all mission records. Retried under the default [`RetryPolicy`] on transient
    /// Postgres errors; reads are naturally idempotent.
    pub async fn list_missions(&self) -> Result<Vec<Mission>> {
        retry(RetryPolicy::default(), || async move {
            Ok(sqlx::query_as!(
                Mission,
                r#"
                SELECT
                    id, created_datetime, modified_datetime, name,
                    start_datetime, end_datetime,
                    position as "position: _", free_text, organization_id
                FROM horizon_public.mission
                "#,
            )
            .fetch_all(&self.pool)
            .await?)
        })
        .await
    }

    /// Read a mission by ID. Retried under the default [`RetryPolicy`] on transient
    /// Postgres errors; reads are naturally idempotent.
    pub async fn read_mission(&self, id: Uuid) -> Result<Option<Mission>> {
        retry(RetryPolicy::default(), || async move {
            Ok(sqlx::query_as!(
                Mission,
                r#"
                SELECT
                    id, created_datetime, modified_datetime, name,
                    start_datetime, end_datetime,
                    position as "position: _", free_text, organization_id
                FROM horizon_public.mission
                WHERE id = $1
                "#,
                id,
            )
            .fetch_optional(&self.pool)
            .await?)
        })
        .await
    }

    /// Update an existing mission by ID.
    ///
    /// Returns `HorizonError::Postgres(PostgresError::NotFound)` if no row
    /// with the given ID exists. Matches Python `BaseRepository.update()`
    /// semantics.
    pub async fn update_mission(&self, mission: &Mission) -> Result<Mission> {
        let now = Utc::now();
        let org = self.organization_id.or(mission.organization_id);
        let pos_x = mission.position.map(|pos| pos.0);
        let pos_y = mission.position.map(|pos| pos.1);
        let result = sqlx::query_as!(
            Mission,
            r#"
            UPDATE horizon_public.mission
            SET
                name = $2,
                start_datetime = $3,
                end_datetime = $4,
                free_text = $5,
                organization_id = $6,
                position = CASE WHEN $7::float8 IS NOT NULL THEN point($7, $8::float8) END,
                modified_datetime = $9
            WHERE id = $1
            RETURNING
                id, created_datetime, modified_datetime, name,
                start_datetime, end_datetime,
                position as "position: _", free_text, organization_id
            "#,
            mission.id,
            mission.name,
            mission.start_datetime,
            mission.end_datetime,
            mission.free_text,
            org,
            pos_x,
            pos_y,
            now,
        )
        .fetch_optional(&self.pool)
        .await?;

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

    /// Create a new mission or update if it already exists.
    pub async fn upsert_mission(&self, mission: &Mission) -> Result<Mission> {
        let now = Utc::now();
        let org = self.organization_id.or(mission.organization_id);
        let pos_x = mission.position.map(|pos| pos.0);
        let pos_y = mission.position.map(|pos| pos.1);
        Ok(sqlx::query_as!(
            Mission,
            r#"
            INSERT INTO horizon_public.mission
                (id, name, start_datetime, end_datetime, free_text,
                 organization_id, position, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5, $6,
                    CASE WHEN $7::float8 IS NOT NULL THEN point($7, $8::float8) END, $9)
            ON CONFLICT (id) DO UPDATE SET
                name = EXCLUDED.name,
                start_datetime = EXCLUDED.start_datetime,
                end_datetime = EXCLUDED.end_datetime,
                free_text = EXCLUDED.free_text,
                organization_id = EXCLUDED.organization_id,
                position = EXCLUDED.position,
                modified_datetime = EXCLUDED.modified_datetime
            RETURNING
                id, created_datetime, modified_datetime, name,
                start_datetime, end_datetime,
                position as "position: _", free_text, organization_id
            "#,
            mission.id,
            mission.name,
            mission.start_datetime,
            mission.end_datetime,
            mission.free_text,
            org,
            pos_x,
            pos_y,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }
}
