use sqlx::PgPool;
use crate::models::Schedule;
use crate::error::{ApiError, Result};

// get_by_date is now handled by ScheduleOperations in utils/db_operations.rs

pub async fn insert_or_update(pool: &PgPool, schedule: &Schedule) -> Result<Schedule> {
    let result = sqlx::query_as!(
        Schedule,
        r#"
        INSERT INTO schedule (
            id, date, song_leader, ss_teacher, ss_leader, mission_story,
            special_program, sermon_speaker, scripture, offering, deacons,
            special_music, childrens_story, afternoon_program, created_at, updated_at
        ) VALUES (
            $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, NOW(), NOW()
        )
        ON CONFLICT (date) DO UPDATE SET
            song_leader = EXCLUDED.song_leader,
            ss_teacher = EXCLUDED.ss_teacher,
            ss_leader = EXCLUDED.ss_leader,
            mission_story = EXCLUDED.mission_story,
            special_program = EXCLUDED.special_program,
            sermon_speaker = EXCLUDED.sermon_speaker,
            scripture = EXCLUDED.scripture,
            offering = EXCLUDED.offering,
            deacons = EXCLUDED.deacons,
            special_music = EXCLUDED.special_music,
            childrens_story = EXCLUDED.childrens_story,
            afternoon_program = EXCLUDED.afternoon_program,
            updated_at = NOW()
        RETURNING *
        "#,
        schedule.id,
        schedule.date,
        schedule.song_leader,
        schedule.ss_teacher,
        schedule.ss_leader,
        schedule.mission_story,
        schedule.special_program,
        schedule.sermon_speaker,
        schedule.scripture,
        schedule.offering,
        schedule.deacons,
        schedule.special_music,
        schedule.childrens_story,
        schedule.afternoon_program
    )
    .fetch_one(pool)
    .await
    .map_err(|e| ApiError::Database(e.to_string()))?;
    
    Ok(result)
}
