     1	import { RestApiResourceError, RestApiValidationError, RestApiPayloadError } from '../../../lib/rest-api-errors.js'
     2	import { findRelationshipDefinition, handleWriteMethodError } from './common.js'
     3	import { createPivotRecords } from '../lib/writing/many-to-many-manipulations.js'
     4	
     5	/**
     6	   * POST RELATIONSHIP
     7	   * Adds members to a to-many relationship
     8	   * POST /api/articles/1/relationships/tags
     9	   *
    10	   * @param {string} id - The ID of the resource
    11	   * @param {string} relationshipName - The name of the relationship
    12	   * @param {array} relationshipData - Array of resource identifiers to add
    13	   * @returns {Promise<void>} 204 No Content
    14	  */
    15	export default async function postRelationshipMethod ({ params, context, vars, helpers, scope, scopes, runHooks, scopeName, api, log }) {
    16	  context.method = 'postRelationship'
    17	  context.id = params.id
    18	  context.relationshipName = params.relationshipName
    19	  context.schemaInfo = scopes[scopeName].vars.schemaInfo
    20	
    21	  // Transaction handling
    22	  context.transaction = params.transaction ||
    23	  (helpers.newTransaction && !params.transaction ? await helpers.newTransaction() : null)
    24	  context.shouldCommit = !params.transaction && !!context.transaction
    25	
    26	  context.db = context.transaction || api.knex.instance
    27	
    28	  try {
    29	  // Validate
    30	    const relDef = findRelationshipDefinition(context.schemaInfo, context.relationshipName)
    31	    if (!relDef) {
    32	      throw new RestApiResourceError(
    33	      `Relationship '${context.relationshipName}' not found on resource '${scopeName}'`,
    34	      { subtype: 'relationship_not_found' }
    35	      )
    36	    }
    37	
    38	    if (relDef.type !== 'hasMany' && relDef.type !== 'manyToMany') {
    39	      throw new RestApiValidationError(
    40	      `Cannot POST to to-one relationship '${context.relationshipName}'. Use PATCH instead.`,
    41	      { fields: ['data'] }
    42	      )
    43	    }
    44	
    45	    if (!Array.isArray(params.relationshipData)) {
    46	      throw new RestApiPayloadError('POST to relationship requires array of resource identifiers')
    47	    }
    48	
    49	    // Check permissions
    50	    await runHooks('checkPermissions')
    51	    await runHooks('checkPermissionsPostRelationship')
    52	
    53	    // Verify parent exists
    54	    const exists = await helpers.dataExists({
    55	      scopeName,
    56	      context: { db: context.db, id: context.id, schemaInfo: context.schemaInfo },
    57	    })
    58	
    59	    if (!exists) {
    60	      throw new RestApiResourceError('Resource not found', { subtype: 'not_found' })
    61	    }
    62	
    63	    // Add relationships
    64	    if (relDef?.through) {
    65	      if (api.anyapi?.links?.attachMany) {
    66	        await api.anyapi.links.attachMany({
    67	          context,
    68	          scopeName,
    69	          relName: context.relationshipName,
    70	          relDef,
    71	          relData: params.relationshipData,
    72	        })
    73	      } else {
    74	        await createPivotRecords(api, context.id, {
    75	          through: relDef.through,
    76	          foreignKey: relDef.foreignKey,
    77	          otherKey: relDef.otherKey
    78	        }, params.relationshipData, context.transaction)
    79	      }
    80	    } else if (relDef.type === 'hasMany') {
    81	      // Update foreign keys for hasMany
    82	      const targetType = relDef.target
    83	      for (const identifier of params.relationshipData) {
    84	        await api.resources[targetType].patch({
    85	          id: identifier.id,
    86	          inputRecord: {
    87	            data: {
    88	              type: targetType,
    89	              id: identifier.id,
    90	              attributes: { [relDef.foreignKey]: context.id }
    91	            }
    92	          },
    93	          transaction: context.transaction,
    94	          simplified: false
    95	        })
    96	      }
    97	    }
    98	
    99	    await runHooks('finish')
   100	    await runHooks('finishPostRelationship')
   101	
   102	    if (context.shouldCommit) {
   103	      await context.transaction.commit()
   104	    }
   105	
   106	    // 204 No Content
   107	  } catch (error) {
   108	    await handleWriteMethodError(error, context, 'POST_RELATIONSHIP', scopeName, log, runHooks)
   109	  }
   110	};
