# Scénario: Modifier un projet
name: projects_update
version: "1.0"
description: Met à jour un projet existant

input:
  required:
    - id
  optional:
    - name
    - description
    - parent_id
    - position
    - tags
  validation:
    id:
      type: int
    name:
      type: string
      min_length: 1
      max_length: 100
    description:
      type: string
      max_length: 65535
    parent_id:
      type: int
    position:
      type: int

steps:
  - id: get_project
    service: db
    action: query_one
    params:
      query: "SELECT * FROM projects WHERE id = ? AND user_id = ?"
      args: ["{{input.id}}", "{{auth.user_id}}"]
    on_error: abort
    error_message: "Projet non trouvé"
    error_status: 404

  - id: check_parent
    service: db
    action: query_one
    condition: "{{input.parent_id != null && input.parent_id != input.id}}"
    params:
      query: "SELECT id FROM projects WHERE id = ? AND user_id = ?"
      args: ["{{input.parent_id}}", "{{auth.user_id}}"]
    on_error: abort
    error_message: "Projet parent invalide"
    error_status: 422

  - id: update_project
    service: db
    action: update
    params:
      table: projects
      where:
        id: "{{input.id}}"
      data:
        name: "{{input.name ?? steps.get_project.result.name}}"
        description: "{{input.description ?? steps.get_project.result.description}}"
        parent_id: "{{input.parent_id ?? steps.get_project.result.parent_id}}"
        position: "{{input.position ?? steps.get_project.result.position}}"

  - id: clear_tags
    service: db
    action: delete
    condition: "{{input.tags != null}}"
    params:
      table: project_tags
      where:
        project_id: "{{input.id}}"

  - id: sync_tags
    service: db
    action: exec
    condition: "{{input.tags != null && input.tags | length > 0}}"
    foreach: "{{input.tags}}"
    foreach_as: tag_id
    params:
      query: |
        INSERT INTO project_tags (project_id, tag_id)
        SELECT ?, id FROM tags WHERE id = ? AND user_id = ?
      args: ["{{input.id}}", "{{tag_id}}", "{{auth.user_id}}"]

  - id: get_updated
    service: db
    action: query_one
    params:
      query: "SELECT * FROM projects WHERE id = ?"
      args: ["{{input.id}}"]

  - id: get_tags
    service: db
    action: query
    params:
      query: |
        SELECT t.id, t.name, t.color
        FROM tags t
        JOIN project_tags pt ON t.id = pt.tag_id
        WHERE pt.project_id = ?
      args: ["{{input.id}}"]

output:
  status: 200
  body:
    success: true
    message: "Projet mis à jour"
    data:
      id: "{{steps.get_updated.result.id}}"
      name: "{{steps.get_updated.result.name}}"
      description: "{{steps.get_updated.result.description}}"
      parent_id: "{{steps.get_updated.result.parent_id}}"
      position: "{{steps.get_updated.result.position}}"
      tags: "{{steps.get_tags.result}}"
