-- ============================================================================
-- SQL для исправления field_name в таблице clpr_claim_documents
-- ============================================================================
-- Проблема: Все документы имеют одинаковый field_name (uploads[0][0])
-- Решение: Пересоздаём записи с правильными field_name на основе documents_uploaded
-- ============================================================================

-- Для конкретного claim_id
WITH claim_data AS (
  SELECT 
    id,
    payload
  FROM clpr_claims
  WHERE id::text = 'bddb6815-8e17-4d54-a721-5e94382942c7'
     OR payload->>'claim_id' = 'bddb6815-8e17-4d54-a721-5e94382942c7'
  ORDER BY updated_at DESC
  LIMIT 1
),

-- Извлекаем documents_required для определения индексов
documents_required_array AS (
  SELECT 
    jsonb_array_elements(payload->'documents_required') WITH ORDINALITY AS doc_req(doc, idx)
  FROM claim_data
),

-- Извлекаем documents_uploaded с правильными индексами
documents_uploaded_mapped AS (
  SELECT 
    doc_up.*,
    (doc_req.idx - 1)::int AS group_index  -- Индекс документа (0-based)
  FROM claim_data,
    jsonb_array_elements(payload->'documents_uploaded') AS doc_up,
    documents_required_array doc_req
  WHERE (doc_up->>'id' = doc_req.doc->>'id' OR doc_up->>'type' = doc_req.doc->>'id')
),

-- Удаляем старые записи
deleted_old AS (
  DELETE FROM clpr_claim_documents
  WHERE claim_id = (SELECT id::text FROM claim_data)
  RETURNING claim_id, field_name, file_id
),

-- Вставляем новые записи с правильными field_name
inserted_new AS (
  INSERT INTO clpr_claim_documents (
    claim_id,
    field_name,
    file_id,
    file_name,
    original_file_name,
    uploaded_at
  )
  SELECT 
    (SELECT id::text FROM claim_data) AS claim_id,
    'uploads[' || group_index || '][0]' AS field_name,
    doc_up->>'file_id' AS file_id,
    doc_up->>'file_name' AS file_name,
    doc_up->>'original_file_name' AS original_file_name,
    COALESCE(
      (doc_up->>'uploaded_at')::timestamptz,
      now()
    ) AS uploaded_at
  FROM documents_uploaded_mapped doc_up
  WHERE doc_up->>'file_id' IS NOT NULL
    AND doc_up->>'file_id' <> ''
  ON CONFLICT (claim_id, field_name) DO UPDATE SET
    file_id = EXCLUDED.file_id,
    file_name = EXCLUDED.file_name,
    original_file_name = EXCLUDED.original_file_name,
    uploaded_at = EXCLUDED.uploaded_at
  RETURNING claim_id, field_name, file_id, file_name
)

-- Возвращаем результат
SELECT 
  'Удалено старых записей' AS action,
  COUNT(*) AS count
FROM deleted_old
UNION ALL
SELECT 
  'Вставлено новых записей' AS action,
  COUNT(*) AS count
FROM inserted_new;

-- Проверка результата
SELECT 
  ccd.claim_id,
  ccd.field_name,
  ccd.file_id,
  ccd.file_name,
  ccd.original_file_name,
  ccd.uploaded_at
FROM clpr_claim_documents ccd
WHERE ccd.claim_id = 'bddb6815-8e17-4d54-a721-5e94382942c7'
ORDER BY ccd.field_name;

