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