-- ============================================================
-- Seed: Migrar de Alibaba OSS a MinIO S3
-- Ejecutar en la base de datos PostgreSQL de producción:
--   psql -h HOST -U usite -d usite -f seed_minio.sql
-- ============================================================

BEGIN;

-- Desactivar configuraciones Alibaba activas
UPDATE oss_api
SET is_active = false,
    notes    = COALESCE(notes, '') || ' [desactivado ' || NOW() || ']'
WHERE provider = 'alibaba'
  AND is_active = true;

-- Insertar nueva configuración MinIO S3
INSERT INTO oss_api (name, provider, endpoint, access_key_id, access_key_secret, bucket_name, region, is_active, public_url, notes, created_at, updated_at)
SELECT 'MinIO - vcardv4',
       's3',
       'http://135.181.2.237:9000',
       'admin',
       'lsE6TAihW98iaXKDWG+6gGLYAFdyp2iC',
       'vcard-usite',
       'us-east-1',
       true,
       NULL,
       'Migrado desde Alibaba OSS el ' || NOW(),
       NOW(),
       NOW()
WHERE NOT EXISTS (
    SELECT 1 FROM oss_api
    WHERE provider = 's3'
      AND endpoint = 'http://135.181.2.237:9000'
      AND deleted_at IS NULL
);

-- Si no se insertó (ya existe), activarla y actualizar credenciales
UPDATE oss_api
SET is_active        = true,
    access_key_id    = 'admin',
    access_key_secret = 'lsE6TAihW98iaXKDWG+6gGLYAFdyp2iC',
    bucket_name      = 'vcard-usite',
    region           = 'us-east-1',
    notes            = 'Actualizado el ' || NOW(),
    updated_at       = NOW()
WHERE provider = 's3'
  AND endpoint = 'http://135.181.2.237:9000'
  AND deleted_at IS NULL
  AND (
    is_active = false
    OR access_key_id != 'admin'
    OR access_key_secret != 'lsE6TAihW98iaXKDWG+6gGLYAFdyp2iC'
  );

COMMIT;

-- Verificación
SELECT id, name, provider, endpoint, bucket_name, is_active, notes
FROM oss_api
WHERE deleted_at IS NULL
ORDER BY id DESC;
