     1	import { toJsonApiRecord } from '../querying/knex-json-api-transformers-querying.js'
     2	import { getSchemaStructure } from './knex-constants.js'
     3	
     4	/**
     5	 * Converts database record to JSON:API format with belongsTo relationships
     6	 *
     7	 * @param {Object} scope - Resource scope with schema and relationship info
     8	 * @param {Object} record - Raw database record
     9	 * @param {string} scopeName - Resource type name
    10	 * @returns {Object} JSON:API resource with belongsTo relationships
    11	 *
    12	 * @example
    13	 * // Input: Database record with foreign keys
    14	 * const dbRecord = {
    15	 *   id: 1,
    16	 *   title: 'Hello World',
    17	 *   author_id: 2,
    18	 *   publisher_id: 3,
    19	 *   category_id: null
    20	 * };
    21	 * const result = toJsonApiRecordWithBelongsTo(scope, dbRecord, 'articles');
    22	 *
    23	 * // Output: JSON:API with relationship objects
    24	 * // {
    25	 * //   type: 'articles',
    26	 * //   id: '1',
    27	 * //   attributes: {
    28	 * //     title: 'Hello World'
    29	 * //     // Note: author_id, publisher_id, category_id removed
    30	 * //   },
    31	 * //   relationships: {
    32	 * //     author: {
    33	 * //       data: { type: 'authors', id: '2' }
    34	 * //     },
    35	 * //     publisher: {
    36	 * //       data: { type: 'publishers', id: '3' }
    37	 * //     },
    38	 * //     category: {
    39	 * //       data: null  // Explicit null for empty relationship
    40	 * //     }
    41	 * //   }
    42	 * // }
    43	 *
    44	 * @example
    45	 * // Input: Polymorphic relationships
    46	 * const dbRecord = {
    47	 *   id: 5,
    48	 *   content: 'Great post!',
    49	 *   commentable_type: 'articles',
    50	 *   commentable_id: 10
    51	 * };
    52	 * // With schema defining polymorphic relationship:
    53	 * // relationships: {
    54	 * //   commentable: {
    55	 * //     belongsToPolymorphic: true,
    56	 * //     typeField: 'commentable_type',
    57	 * //     idField: 'commentable_id'
    58	 * //   }
    59	 * // }
    60	 *
    61	 * // Output: Polymorphic relationship in JSON:API
    62	 * // {
    63	 * //   type: 'comments',
    64	 * //   id: '5',
    65	 * //   attributes: { content: 'Great post!' },
    66	 * //   relationships: {
    67	 * //     commentable: {
    68	 * //       data: { type: 'articles', id: '10' }
    69	 * //     }
    70	 * //   }
    71	 * // }
    72	 *
    73	 * @description
    74	 * Used by:
    75	 * - dataGetMinimal for lightweight single record fetches
    76	 * - dataDelete to return deleted record structure
    77	 * - Internal operations needing quick JSON:API conversion
    78	 *
    79	 * Purpose:
    80	 * - Provides JSON:API structure without loading related data
    81	 * - Transforms foreign keys into relationship objects
    82	 * - Handles both regular and polymorphic belongsTo
    83	 * - Maintains explicit nulls for empty relationships
    84	 *
    85	 * Data flow:
    86	 * 1. Calls toJsonApiRecord for basic transformation
    87	 * 2. Scans schema for belongsTo field definitions
    88	 * 3. Converts foreign key values to relationship objects
    89	 * 4. Processes polymorphic relationships separately
    90	 * 5. Returns complete JSON:API resource object
    91	 */
    92	export const toJsonApiRecordWithBelongsTo = (scope, record, scopeName) => {
    93	  if (!record) return null
    94	
    95	  // Get the basic JSON:API structure (without relationships)
    96	  const jsonApiRecord = toJsonApiRecord(scope, record, scopeName)
    97	
    98	  // Extract schema info from scope
    99	  const {
   100	    vars: {
   101	      schemaInfo: { schemaInstance, schemaRelationships: relationships, idProperty }
   102	    }
   103	  } = scope
   104	
   105	  const idField = idProperty || 'id'
   106	
   107	  // Get schema structure
   108	  const schemaStructure = getSchemaStructure(schemaInstance)
   109	
   110	  // Initialize relationships object
   111	  jsonApiRecord.relationships = {}
   112	
   113	  // Process regular belongsTo relationships from schema
   114	  for (const [fieldName, fieldDef] of Object.entries(schemaStructure)) {
   115	    if (fieldDef.belongsTo && fieldDef.as) {
   116	      const foreignKeyValue = record[fieldName]
   117	
   118	      if (foreignKeyValue !== null && foreignKeyValue !== undefined) {
   119	        jsonApiRecord.relationships[fieldDef.as] = {
   120	          data: {
   121	            type: fieldDef.belongsTo,
   122	            id: String(foreignKeyValue)
   123	          }
   124	        }
   125	      } else {
   126	        // Explicitly null relationship
   127	        jsonApiRecord.relationships[fieldDef.as] = {
   128	          data: null
   129	        }
   130	      }
   131	    }
   132	  }
   133	
   134	  // Process polymorphic belongsTo relationships
   135	  Object.entries(relationships || {}).forEach(([relName, relDef]) => {
   136	    if (relDef.belongsToPolymorphic) {
   137	      const typeValue = record[relDef.typeField]
   138	      const idValue = record[relDef.idField]
   139	
   140	      if (typeValue && idValue) {
   141	        jsonApiRecord.relationships[relName] = {
   142	          data: {
   143	            type: typeValue,
   144	            id: String(idValue)
   145	          }
   146	        }
   147	      } else {
   148	        // Explicitly null relationship
   149	        jsonApiRecord.relationships[relName] = {
   150	          data: null
   151	        }
   152	      }
   153	    }
   154	  })
   155	
   156	  // Remove relationships object if empty
   157	  if (Object.keys(jsonApiRecord.relationships).length === 0) {
   158	    delete jsonApiRecord.relationships
   159	  }
   160	
   161	  return jsonApiRecord
   162	}
