course-service 0.2.0

Course Service — a course-administration microservice modelled on schema.org/Course; interoperates with the course-matcher crate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! Database access — connection pool + repository.
//!
//! `SeaOrmCourseRepository` round-trips a domain [`Course`] against the
//! relational schema: scalar fields and JSONB collections live on the
//! `courses` row; `identifiers` and `links` live in their own child
//! tables. Sub-resources (`instances`, `syllabus_sections`) have their
//! own dedicated API surface and are intentionally not loaded here —
//! they ship with T-8.

use chrono::Utc;
use sea_orm::{
    ActiveModelTrait, ActiveValue::Set, ColumnTrait, Database, DatabaseConnection, EntityTrait,
    QueryFilter, QueryOrder, QuerySelect, TransactionTrait,
};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::Result;
use crate::config::DatabaseConfig;
use crate::models::{
    Course, CourseIdentifier, CourseInstance, CourseInstanceStatus, CourseLink, CourseMode,
    CourseStatus, EducationalLevel, IdentifierType, InteractivityType, LearningResourceType,
    LinkType, MergeRecord, Schedule,
};

pub mod audit;
pub mod models;

use models::{course_identifiers, course_instances, course_links, course_merge_records, courses};

/// Open a connection pool from a `DatabaseConfig`.
pub async fn create_connection(config: &DatabaseConfig) -> Result<DatabaseConnection> {
    let mut opt = sea_orm::ConnectOptions::new(&config.url);
    opt.max_connections(config.max_connections)
        .min_connections(config.min_connections);
    Database::connect(opt)
        .await
        .map_err(|e| crate::Error::Pool(e.to_string()))
}

/// Repository for Course CRUD.
///
/// `dyn`-compatibility provided by `async_trait` (object-safety
/// blocks plain `async fn` in trait methods until we move to RPITIT).
#[async_trait::async_trait]
pub trait CourseRepository: Send + Sync {
    /// Insert a new course (plus its identifier/link child rows).
    async fn create(&self, course: &Course) -> Result<Course>;
    /// Fetch a course by id, returning `None` if absent or soft-deleted.
    async fn get_by_id(&self, id: &Uuid) -> Result<Option<Course>>;
    /// Update an existing course, replacing its child rows.
    async fn update(&self, course: &Course) -> Result<Course>;
    /// Soft-delete a course (sets `deleted_at`, clears `active`).
    async fn soft_delete(&self, id: &Uuid) -> Result<()>;
    /// List non-deleted courses, newest first, with limit/offset paging.
    async fn list(&self, limit: u64, offset: u64) -> Result<Vec<Course>>;

    // CourseInstance sub-resource (T-8, FR-10..FR-13).
    /// List a course's non-deleted instances (FR-10 ordering applied).
    async fn list_instances(&self, course_id: &Uuid) -> Result<Vec<CourseInstance>>;
    /// Fetch one instance scoped to its parent course.
    async fn get_instance(
        &self,
        course_id: &Uuid,
        instance_id: &Uuid,
    ) -> Result<Option<CourseInstance>>;
    /// Insert a new instance under its parent course.
    async fn create_instance(&self, instance: &CourseInstance) -> Result<CourseInstance>;
    /// Update an existing instance.
    async fn update_instance(&self, instance: &CourseInstance) -> Result<CourseInstance>;
    /// Soft-delete one instance scoped to its parent course.
    async fn soft_delete_instance(
        &self,
        course_id: &Uuid,
        instance_id: &Uuid,
    ) -> Result<()>;

    /// Merge bookkeeping (T-7b / FR-8). Inserts a row into
    /// `course_merge_records` describing the fold of `duplicate` into
    /// `main`. The handler is responsible for the actual data
    /// transfer + soft-delete of the duplicate.
    async fn record_merge(&self, rec: &MergeRecord) -> Result<MergeRecord>;
}

/// SeaORM-backed [`CourseRepository`] implementation over a PostgreSQL
/// connection pool.
pub struct SeaOrmCourseRepository {
    /// The shared SeaORM connection pool.
    db: DatabaseConnection,
}

impl SeaOrmCourseRepository {
    /// Wrap an existing connection pool in a repository.
    pub fn new(db: DatabaseConnection) -> Self {
        Self { db }
    }
}

#[async_trait::async_trait]
impl CourseRepository for SeaOrmCourseRepository {
    async fn create(&self, course: &Course) -> Result<Course> {
        let txn = self.db.begin().await.map_err(map_db)?;
        let active = to_course_active(course, false)?;
        active.insert(&txn).await.map_err(map_db)?;
        insert_identifiers(&txn, course.id, &course.identifiers).await?;
        insert_links(&txn, course.id, &course.links).await?;
        txn.commit().await.map_err(map_db)?;
        self.get_by_id(&course.id)
            .await?
            .ok_or_else(|| crate::Error::Database("course not found after insert".into()))
    }

    async fn get_by_id(&self, id: &Uuid) -> Result<Option<Course>> {
        let row = courses::Entity::find_by_id(*id)
            .one(&self.db)
            .await
            .map_err(map_db)?;
        let Some(row) = row else { return Ok(None) };
        if row.deleted_at.is_some() {
            return Ok(None);
        }
        let identifiers = load_identifiers(&self.db, *id).await?;
        let links = load_links(&self.db, *id).await?;
        Ok(Some(hydrate_course(row, identifiers, links)?))
    }

    async fn update(&self, course: &Course) -> Result<Course> {
        let exists = courses::Entity::find_by_id(course.id)
            .one(&self.db)
            .await
            .map_err(map_db)?;
        if exists.is_none() {
            return Err(crate::Error::NotFound);
        }
        let txn = self.db.begin().await.map_err(map_db)?;
        let active = to_course_active(course, true)?;
        active.update(&txn).await.map_err(map_db)?;
        course_identifiers::Entity::delete_many()
            .filter(course_identifiers::Column::CourseId.eq(course.id))
            .exec(&txn)
            .await
            .map_err(map_db)?;
        course_links::Entity::delete_many()
            .filter(course_links::Column::CourseId.eq(course.id))
            .exec(&txn)
            .await
            .map_err(map_db)?;
        insert_identifiers(&txn, course.id, &course.identifiers).await?;
        insert_links(&txn, course.id, &course.links).await?;
        txn.commit().await.map_err(map_db)?;
        self.get_by_id(&course.id)
            .await?
            .ok_or(crate::Error::NotFound)
    }

    async fn soft_delete(&self, id: &Uuid) -> Result<()> {
        let row = courses::Entity::find_by_id(*id)
            .one(&self.db)
            .await
            .map_err(map_db)?
            .ok_or(crate::Error::NotFound)?;
        let mut active: courses::ActiveModel = row.into();
        active.active = Set(false);
        active.deleted_at = Set(Some(Utc::now()));
        active.updated_at = Set(Utc::now());
        active.update(&self.db).await.map_err(map_db)?;
        Ok(())
    }

    async fn list(&self, limit: u64, offset: u64) -> Result<Vec<Course>> {
        let rows = courses::Entity::find()
            .filter(courses::Column::DeletedAt.is_null())
            .order_by_desc(courses::Column::CreatedAt)
            .limit(limit)
            .offset(offset)
            .all(&self.db)
            .await
            .map_err(map_db)?;
        let mut out = Vec::with_capacity(rows.len());
        for row in rows {
            let id = row.id;
            let identifiers = load_identifiers(&self.db, id).await?;
            let links = load_links(&self.db, id).await?;
            out.push(hydrate_course(row, identifiers, links)?);
        }
        Ok(out)
    }

    // ──────────── CourseInstance sub-resource ────────────

    async fn list_instances(&self, course_id: &Uuid) -> Result<Vec<CourseInstance>> {
        let rows = course_instances::Entity::find()
            .filter(course_instances::Column::CourseId.eq(*course_id))
            .filter(course_instances::Column::DeletedAt.is_null())
            .all(&self.db)
            .await
            .map_err(map_db)?;
        let mut out = rows
            .into_iter()
            .map(hydrate_instance)
            .collect::<Result<Vec<_>>>()?;
        // FR-10 — `schedule.start_date DESC NULLS LAST`. Schedule is
        // JSONB so we sort in-memory after hydration.
        out.sort_by(|a, b| schedule_start(b).cmp(&schedule_start(a)));
        Ok(out)
    }

    async fn get_instance(
        &self,
        course_id: &Uuid,
        instance_id: &Uuid,
    ) -> Result<Option<CourseInstance>> {
        let row = course_instances::Entity::find_by_id(*instance_id)
            .filter(course_instances::Column::CourseId.eq(*course_id))
            .one(&self.db)
            .await
            .map_err(map_db)?;
        let Some(row) = row else { return Ok(None) };
        if row.deleted_at.is_some() {
            return Ok(None);
        }
        Ok(Some(hydrate_instance(row)?))
    }

    async fn create_instance(&self, instance: &CourseInstance) -> Result<CourseInstance> {
        let active = to_instance_active(instance, false)?;
        active.insert(&self.db).await.map_err(map_db)?;
        self.get_instance(&instance.course_id, &instance.id)
            .await?
            .ok_or_else(|| crate::Error::Database("instance not found after insert".into()))
    }

    async fn update_instance(&self, instance: &CourseInstance) -> Result<CourseInstance> {
        let exists = course_instances::Entity::find_by_id(instance.id)
            .filter(course_instances::Column::CourseId.eq(instance.course_id))
            .one(&self.db)
            .await
            .map_err(map_db)?;
        let Some(row) = exists else { return Err(crate::Error::NotFound) };
        if row.deleted_at.is_some() {
            return Err(crate::Error::NotFound);
        }
        let active = to_instance_active(instance, true)?;
        active.update(&self.db).await.map_err(map_db)?;
        self.get_instance(&instance.course_id, &instance.id)
            .await?
            .ok_or(crate::Error::NotFound)
    }

    async fn soft_delete_instance(
        &self,
        course_id: &Uuid,
        instance_id: &Uuid,
    ) -> Result<()> {
        let row = course_instances::Entity::find_by_id(*instance_id)
            .filter(course_instances::Column::CourseId.eq(*course_id))
            .one(&self.db)
            .await
            .map_err(map_db)?
            .ok_or(crate::Error::NotFound)?;
        if row.deleted_at.is_some() {
            return Err(crate::Error::NotFound);
        }
        let mut active: course_instances::ActiveModel = row.into();
        active.deleted_at = Set(Some(Utc::now()));
        active.updated_at = Set(Utc::now());
        active.update(&self.db).await.map_err(map_db)?;
        Ok(())
    }

    async fn record_merge(&self, rec: &MergeRecord) -> Result<MergeRecord> {
        let active = course_merge_records::ActiveModel {
            id: Set(rec.id),
            main_course_id: Set(rec.main_course_id),
            duplicate_course_id: Set(rec.duplicate_course_id),
            status: Set(enum_to_string(&rec.status)?),
            merged_by: Set(rec.merged_by.clone()),
            merge_reason: Set(rec.merge_reason.clone()),
            match_score: Set(rec.match_score),
            transferred_data: Set(rec.transferred_data.clone()),
            merged_at: Set(rec.merged_at),
        };
        active.insert(&self.db).await.map_err(map_db)?;
        Ok(rec.clone())
    }
}

/// Pull an instance's schedule start date for FR-10 in-memory sorting.
fn schedule_start(i: &CourseInstance) -> Option<chrono::DateTime<chrono::Utc>> {
    i.schedule.as_ref().and_then(|s| s.start_date)
}

// ────────────────── Domain ↔ DB conversion ──────────────────

/// Build a `courses` SeaORM `ActiveModel` from a domain [`Course`],
/// serialising collection fields to JSONB. On update, `updated_at` is
/// stamped to now; on insert the model's own timestamp is kept.
fn to_course_active(course: &Course, is_update: bool) -> Result<courses::ActiveModel> {
    let now = Utc::now();
    Ok(courses::ActiveModel {
        id: Set(course.id),
        name: Set(course.name.clone()),
        alternate_names: Set(to_json(&course.alternate_names)?),
        description: Set(course.description.clone()),
        disambiguating_description: Set(course.disambiguating_description.clone()),
        url: Set(course.url.clone()),
        image: Set(to_json(&course.image)?),
        same_as: Set(to_json(&course.same_as)?),
        keywords: Set(to_json(&course.keywords)?),
        additional_type: Set(course.additional_type.clone()),
        about: Set(to_json(&course.about)?),
        audience: Set(course.audience.clone()),
        in_language: Set(to_json(&course.in_language)?),
        license: Set(course.license.clone()),
        typical_age_range: Set(course.typical_age_range.clone()),
        time_required: Set(course.time_required.clone()),
        version: Set(course.version.clone()),
        is_accessible_for_free: Set(course.is_accessible_for_free),
        teaches: Set(to_json(&course.teaches)?),
        assesses: Set(to_json(&course.assesses)?),
        competency_required: Set(to_json(&course.competency_required)?),
        educational_level: Set(course
            .educational_level
            .as_ref()
            .map(to_json)
            .transpose()?),
        educational_use: Set(course.educational_use.clone()),
        learning_resource_type: Set(course
            .learning_resource_type
            .as_ref()
            .map(to_json)
            .transpose()?),
        interactivity_type: Set(course
            .interactivity_type
            .as_ref()
            .map(enum_to_string)
            .transpose()?),
        course_code: Set(course.course_code.clone()),
        number_of_credits: Set(course.number_of_credits.map(|v| v as i32)),
        course_prerequisites: Set(to_json(&course.course_prerequisites)?),
        available_language: Set(to_json(&course.available_language)?),
        financial_aid_eligible: Set(to_json(&course.financial_aid_eligible)?),
        educational_credential_awarded: Set(course
            .educational_credential_awarded
            .as_ref()
            .map(to_json)
            .transpose()?),
        occupational_credential_awarded: Set(course
            .occupational_credential_awarded
            .as_ref()
            .map(to_json)
            .transpose()?),
        total_historical_enrollment: Set(course.total_historical_enrollment.map(|v| v as i64)),
        status: Set(enum_to_string(&course.status)?),
        active: Set(course.active),
        provider_id: Set(course.provider_id),
        created_at: Set(course.created_at),
        updated_at: Set(if is_update { now } else { course.updated_at }),
        deleted_at: Set(course.deleted_at),
    })
}

/// Reconstruct a domain [`Course`] from its `courses` row plus the
/// child identifier/link collections, deserialising JSONB columns.
/// Sub-resources (`syllabus_sections`, `instances`) are left empty —
/// they load via their own endpoints.
fn hydrate_course(
    row: courses::Model,
    identifiers: Vec<CourseIdentifier>,
    links: Vec<CourseLink>,
) -> Result<Course> {
    Ok(Course {
        id: row.id,
        name: row.name,
        alternate_names: from_json(row.alternate_names)?,
        description: row.description,
        disambiguating_description: row.disambiguating_description,
        url: row.url,
        image: from_json(row.image)?,
        same_as: from_json(row.same_as)?,
        keywords: from_json(row.keywords)?,
        identifiers,
        additional_type: row.additional_type,
        active: row.active,
        about: from_json(row.about)?,
        audience: row.audience,
        in_language: from_json(row.in_language)?,
        license: row.license,
        typical_age_range: row.typical_age_range,
        time_required: row.time_required,
        version: row.version,
        is_accessible_for_free: row.is_accessible_for_free,
        teaches: from_json(row.teaches)?,
        assesses: from_json(row.assesses)?,
        competency_required: from_json(row.competency_required)?,
        educational_level: row.educational_level.map(from_json::<EducationalLevel>).transpose()?,
        educational_use: row.educational_use,
        learning_resource_type: row
            .learning_resource_type
            .map(from_json::<LearningResourceType>)
            .transpose()?,
        interactivity_type: row
            .interactivity_type
            .as_deref()
            .map(enum_from_string::<InteractivityType>)
            .transpose()?,
        course_code: row.course_code,
        number_of_credits: row.number_of_credits.map(|v| v as u32),
        course_prerequisites: from_json(row.course_prerequisites)?,
        available_language: from_json(row.available_language)?,
        financial_aid_eligible: from_json(row.financial_aid_eligible)?,
        educational_credential_awarded: row
            .educational_credential_awarded
            .map(from_json)
            .transpose()?,
        occupational_credential_awarded: row
            .occupational_credential_awarded
            .map(from_json)
            .transpose()?,
        total_historical_enrollment: row.total_historical_enrollment.map(|v| v as u64),
        syllabus_sections: vec![],
        instances: vec![],
        status: enum_from_string::<CourseStatus>(&row.status)?,
        links,
        provider_id: row.provider_id,
        deleted_at: row.deleted_at,
        created_at: row.created_at,
        updated_at: row.updated_at,
    })
}

// ────────────────── Instance round-trip ──────────────────

/// Build a `course_instances` `ActiveModel` from a domain
/// [`CourseInstance`], serialising collection/schedule fields to JSONB.
fn to_instance_active(
    i: &CourseInstance,
    is_update: bool,
) -> Result<course_instances::ActiveModel> {
    let now = Utc::now();
    Ok(course_instances::ActiveModel {
        id: Set(i.id),
        course_id: Set(i.course_id),
        name: Set(i.name.clone()),
        course_mode: Set(i.course_mode.as_ref().map(enum_to_string).transpose()?),
        status: Set(enum_to_string(&i.status)?),
        in_language: Set(to_json(&i.in_language)?),
        location: Set(i.location.clone()),
        location_id: Set(i.location_id),
        instructor_ids: Set(to_json(&i.instructor_ids)?),
        instructor_names: Set(to_json(&i.instructor_names)?),
        maximum_attendee_capacity: Set(i.maximum_attendee_capacity.map(|v| v as i32)),
        enrolled_count: Set(i.enrolled_count.map(|v| v as i32)),
        enrollment_opens: Set(i.enrollment_opens),
        enrollment_closes: Set(i.enrollment_closes),
        schedule: Set(i.schedule.as_ref().map(to_json).transpose()?),
        created_at: Set(i.created_at),
        updated_at: Set(if is_update { now } else { i.updated_at }),
        deleted_at: Set(None),
    })
}

/// Reconstruct a domain [`CourseInstance`] from its row, deserialising
/// JSONB columns and widening the stored `i32` counts back to `u32`.
fn hydrate_instance(row: course_instances::Model) -> Result<CourseInstance> {
    Ok(CourseInstance {
        id: row.id,
        course_id: row.course_id,
        name: row.name,
        course_mode: row
            .course_mode
            .as_deref()
            .map(enum_from_string::<CourseMode>)
            .transpose()?,
        status: enum_from_string::<CourseInstanceStatus>(&row.status)?,
        in_language: from_json(row.in_language)?,
        location: row.location,
        location_id: row.location_id,
        instructor_ids: from_json(row.instructor_ids)?,
        instructor_names: from_json(row.instructor_names)?,
        maximum_attendee_capacity: row.maximum_attendee_capacity.map(|v| v as u32),
        enrolled_count: row.enrolled_count.map(|v| v as u32),
        enrollment_opens: row.enrollment_opens,
        enrollment_closes: row.enrollment_closes,
        schedule: row.schedule.map(from_json::<Schedule>).transpose()?,
        created_at: row.created_at,
        updated_at: row.updated_at,
    })
}

// ────────────────── Child-table round-trip ──────────────────

/// Insert each [`CourseIdentifier`] as a `course_identifiers` child row
/// under `course_id`. Generic over the connection so it runs inside a
/// transaction.
async fn insert_identifiers<C>(
    conn: &C,
    course_id: Uuid,
    identifiers: &[CourseIdentifier],
) -> Result<()>
where
    C: sea_orm::ConnectionTrait,
{
    for ident in identifiers {
        let row = course_identifiers::ActiveModel {
            id: Set(Uuid::new_v4()),
            course_id: Set(course_id),
            property_id: Set(to_json(&ident.property_id)?),
            value: Set(ident.value.clone()),
            name: Set(ident.name.clone()),
            url: Set(ident.url.clone()),
            created_at: Set(Utc::now()),
        };
        row.insert(conn).await.map_err(map_db)?;
    }
    Ok(())
}

/// Insert each [`CourseLink`] as a `course_links` child row under
/// `course_id`. Generic over the connection so it runs in a transaction.
async fn insert_links<C>(conn: &C, course_id: Uuid, links: &[CourseLink]) -> Result<()>
where
    C: sea_orm::ConnectionTrait,
{
    for link in links {
        let row = course_links::ActiveModel {
            id: Set(Uuid::new_v4()),
            course_id: Set(course_id),
            other_course_id: Set(link.other_course_id),
            link_type: Set(enum_to_string(&link.link_type)?),
            created_at: Set(Utc::now()),
        };
        row.insert(conn).await.map_err(map_db)?;
    }
    Ok(())
}

/// Load and deserialise all `course_identifiers` rows for `course_id`.
async fn load_identifiers(
    db: &DatabaseConnection,
    course_id: Uuid,
) -> Result<Vec<CourseIdentifier>> {
    let rows = course_identifiers::Entity::find()
        .filter(course_identifiers::Column::CourseId.eq(course_id))
        .all(db)
        .await
        .map_err(map_db)?;
    rows.into_iter()
        .map(|r| {
            Ok(CourseIdentifier {
                property_id: from_json::<IdentifierType>(r.property_id)?,
                value: r.value,
                name: r.name,
                url: r.url,
            })
        })
        .collect()
}

/// Load and deserialise all `course_links` rows for `course_id`.
async fn load_links(db: &DatabaseConnection, course_id: Uuid) -> Result<Vec<CourseLink>> {
    let rows = course_links::Entity::find()
        .filter(course_links::Column::CourseId.eq(course_id))
        .all(db)
        .await
        .map_err(map_db)?;
    rows.into_iter()
        .map(|r| {
            Ok(CourseLink {
                other_course_id: r.other_course_id,
                link_type: enum_from_string::<LinkType>(&r.link_type)?,
            })
        })
        .collect()
}

// ────────────────── Helpers ──────────────────

/// Map a SeaORM error into the crate's [`Error::Database`](crate::Error).
fn map_db(e: sea_orm::DbErr) -> crate::Error {
    crate::Error::Database(e.to_string())
}

/// Serialise a value to a JSONB `serde_json::Value`, mapping failures to
/// [`Error::Database`](crate::Error).
fn to_json<T: Serialize>(v: &T) -> Result<serde_json::Value> {
    serde_json::to_value(v).map_err(|e| crate::Error::Database(e.to_string()))
}

/// Deserialise a JSONB value back into `T`, mapping failures to
/// [`Error::Database`](crate::Error).
fn from_json<T: for<'de> Deserialize<'de>>(j: serde_json::Value) -> Result<T> {
    serde_json::from_value(j).map_err(|e| crate::Error::Database(e.to_string()))
}

/// Serialise a string-valued enum to its bare string form (used for
/// `status`-style columns stored as `TEXT` rather than JSONB).
fn enum_to_string<T: Serialize>(v: &T) -> Result<String> {
    let json = serde_json::to_value(v).map_err(|e| crate::Error::Database(e.to_string()))?;
    json.as_str()
        .map(|s| s.to_string())
        .ok_or_else(|| crate::Error::Database("enum did not serialise to a string".into()))
}

/// Inverse of [`enum_to_string`]: parse a bare string back into a
/// string-valued enum `T`.
fn enum_from_string<T: for<'de> Deserialize<'de>>(s: &str) -> Result<T> {
    serde_json::from_value(serde_json::Value::String(s.to_string()))
        .map_err(|e| crate::Error::Database(e.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::CourseStatus;

    /// Every `CourseStatus` survives an enum→string→enum round-trip.
    #[test]
    fn course_status_round_trips_through_string() {
        for status in [
            CourseStatus::Draft,
            CourseStatus::Published,
            CourseStatus::Archived,
            CourseStatus::Retired,
        ] {
            let s = enum_to_string(&status).unwrap();
            let back: CourseStatus = enum_from_string(&s).unwrap();
            assert_eq!(status, back, "{s} did not round-trip");
        }
    }

    /// Every `LinkType` survives an enum→string→enum round-trip.
    #[test]
    fn link_type_round_trips_through_string() {
        for lt in [
            LinkType::Replaces,
            LinkType::ReplacedBy,
            LinkType::Seealso,
            LinkType::Prerequisite,
            LinkType::Successor,
        ] {
            let s = enum_to_string(&lt).unwrap();
            let back: LinkType = enum_from_string(&s).unwrap();
            assert_eq!(lt, back, "{s} did not round-trip");
        }
    }

    /// `to_course_active` copies scalar fields onto the ActiveModel.
    #[test]
    fn course_active_model_carries_all_scalar_fields() {
        let mut course = Course::new("Intro to CS");
        course.course_code = Some("CS101".into());
        course.number_of_credits = Some(3);
        course.educational_level = Some(EducationalLevel::Undergraduate);
        course.keywords = vec!["programming".into(), "algorithms".into()];
        let active = to_course_active(&course, false).unwrap();
        assert!(matches!(active.name, Set(ref n) if n == "Intro to CS"));
        assert!(matches!(active.course_code, Set(Some(ref c)) if c == "CS101"));
        assert!(matches!(active.number_of_credits, Set(Some(3))));
        assert!(matches!(active.status, Set(ref s) if s == "published"));
    }
}