SET @login_logs_exists := (
  SELECT COUNT(*)
  FROM information_schema.tables
  WHERE table_schema = DATABASE()
    AND table_name = 'login_logs'
);

SET @merge_login_logs_sql := IF(
  @login_logs_exists > 0,
  'INSERT INTO audit_logs (
    actor_id,
    actor_username,
    action,
    resource_type,
    resource_id,
    metadata,
    ip_address,
    created_at
  )
  SELECT
    login_logs.user_id,
    login_logs.username,
    ''auth.login'',
    ''user'',
    login_logs.user_id,
    JSON_OBJECT(
      ''loginResult'', login_logs.result,
      ''loginName'', login_logs.username,
      ''failureReason'', login_logs.failure_reason,
      ''userAgent'', login_logs.user_agent,
      ''migratedFrom'', ''login_logs''
    ),
    login_logs.ip_address,
    login_logs.created_at
  FROM login_logs
  WHERE NOT EXISTS (
    SELECT 1
    FROM audit_logs
    WHERE audit_logs.action = ''auth.login''
      AND audit_logs.created_at = login_logs.created_at
      AND JSON_UNQUOTE(JSON_EXTRACT(audit_logs.metadata, ''$.loginName'')) = login_logs.username
      AND JSON_UNQUOTE(JSON_EXTRACT(audit_logs.metadata, ''$.loginResult'')) = login_logs.result
  )',
  'SELECT 1'
);
PREPARE merge_login_logs_stmt FROM @merge_login_logs_sql;
EXECUTE merge_login_logs_stmt;
DEALLOCATE PREPARE merge_login_logs_stmt;

UPDATE roles
SET permissions = JSON_REMOVE(permissions, '$."admin/login-logs"')
WHERE JSON_CONTAINS_PATH(permissions, 'one', '$."admin/login-logs"');

UPDATE roles
SET permissions = JSON_SET(
  COALESCE(permissions, JSON_OBJECT()),
  '$."admin/audit-logs"',
  JSON_ARRAY('read')
)
WHERE code = 'super_admin';

SET @drop_login_logs_sql := IF(
  @login_logs_exists > 0,
  'DROP TABLE login_logs',
  'SELECT 1'
);
PREPARE drop_login_logs_stmt FROM @drop_login_logs_sql;
EXECUTE drop_login_logs_stmt;
DEALLOCATE PREPARE drop_login_logs_stmt;
